快速排序由C. A. R. Hoare在1960年提出。它的基本思想是:通過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的所有數據都比另外一部分的所有數據都要小,然後再按此方法對這兩部分數據分別進行快速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。
直接上乾貨!
1. C語言:
#include <stdio.h>
#include <stdlib.h>
void QSort(int A[],int Low,int High)
{
int i,j,P;
if(Low>=High) return;
i=Low;j=High;
P=A[Low];
while(i<j)
{
while(i<j && P<=A[j]) j--;
if(i<j) {A[i]=A[j];i++; }
while(i<j && A[i]<P) i++;
if(i<j) {A[j]=A[i];j--; }
}
A[i]=P;
QSort(A,Low,i-1);
QSort(A,i+1,High);
}
main()
{
int a[]={49,38,65,97,76,13,27,49},i;
QSort(a,0,7);
for(i=0;i<8;i++)
printf("%d ",a[i]);
printf("\n");
}
2. C#語言:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 快速排序
{
class elemtype
{
public int low, high;
public elemtype()
{
low = 0; high = 0;
}
public elemtype(int LOW, int HIGH)
{
low = LOW; high = HIGH;
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 快速排序
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int QSwap(int []A,int pLow,int pHigh)
{
int i,j,P;
if (pLow>=pHigh) return -1;
i=pLow;j=pHigh;P=A[i];
while(i<j)
{
while(i<j && P<=A[j]) j--; //右邊的小於支點前移動
if(i<j) {A[i]=A[j];i++; }
while(i<j && A[i]<P) i++; //左邊的大於支點後移動
if(i<j) {A[j]=A[i];j--; }
}
A[i]=P; //最後確定的位置放支點數據
return i;
}
public void SQSort(int []A,int n)
{
//Stack<int>s=new Stack<int>();
Stack<elemtype> s = new Stack<elemtype>();
int m,low,high;
elemtype E=new elemtype ();
low=0;high=n-1;
E.high=n-1;
E.low=0;
s.Push(E);
while(s.Count!=0)
{
E = new elemtype();
E = s.Pop();
high=E.high;
low=E.low;
m=QSwap(A,low,high);
if(m>0)
{
E = new elemtype();
E.low=low; //支點左邊數據位置進棧
E.high=m-1;
s.Push(E);
E = new elemtype();
E.low =m+1; //支點右邊數據位置進棧
E.high=high;
s.Push(E);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
int i,m;
int []a={49,38,65,97,76,13,27,49}; //快速排序測試數據
SQSort(a,8);
listBox1.Items.Clear();
for (i = 0; i < 8; i++)
listBox1.Items.Add(a[i].ToString());
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}