虽然用 c写的但是用了引用 要在c++环境中 跑
主要是结合
#include<stdio.h>
#define MaxSize 20 //顺序表最大长度
typedef int KeyType; //typedef定义关键字类型为(int)
typedef int InfoType;
typedef struct
{
KeyType key; //关键字项
InfoType otherinfo; //其他数据项
}RedType;
typedef struct
{
RedType r[MaxSize + 1]; //r[0]闲置或做哨兵单元
int length; //顺序表的长度
}SqList; //顺序表类型
int partion(SqList &s, int low, int high) {
s.r[0] = s.r[low];
while (low < high) {
while (low < high && s.r[high].key >= s.r[0].key) {
high--;
}
if (low < high) {
s.r[low] = s.r[high];
low++;//有的教材这里没有写 写了会少比较一次 例如下面
}
while (low < high && s.r[low].key <= s.r[0].key) {
low++;
}
if (low < high) {
s.r[high] = s.r[low];
high--; ;//有的教材这里没有写 写了会少比较一次
}
}
s.r[low] = s.r[0];
for (int i = 1; i <= s.length; i++)
printf("%d ", s.r[i].key);
printf("\n");
return low;
}
void qSort(SqList &s, int low, int high) {
int p;
if (low < high) {
p = partion(s, low, high);
qSort(s, low, p - 1);
qSort(s, p + 1, high);
}
}
int main()
{
//快速排序测试
SqList L;
L.length = 10;
L.r[1].key = 45;
L.r[2].key = 53;
L.r[3].key = 18;
L.r[4].key = 49;
L.r[5].key = 36;
L.r[6].key = 76;
L.r[7].key = 13;
L.r[8].key = 97;
L.r[9].key = 36;
L.r[10].key = 32;
for (int i = 1; i <= L.length; i++)
printf("%d ", L.r[i].key);
printf("\n");
printf("\n");
printf("\n");
printf("\n");
qSort(L, 1, 10);
}
java 实现快速排序
public class QuickSort { public static int partition(List<Integer> list, int low, int high) { int m = list.get(low); while (low < high) { while (low < high && list.get(high) > m) { high--; } if (low < high) { list.set(low, list.get(high)); low++; } while (low < high && list.get(low) < m) { low++; } if (low < high) { list.set(high, list.get(low)); high--; } } list.set(low, m); return low; } public static void quickSort(List<Integer> list, int low, int high) { int p; if (low < high){ p = partition(list, low, high); quickSort(list,low, p-1); quickSort(list,p+1, high); } } public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(0, 8); list.add(1, 9); list.add(2, 1); list.add(3, 7); list.add(4, 2); list.add(5, 3); list.add(6, 5); list.add(7, 4); list.add(8, 6); list.add(9, 55); list.add(10, 6); list.add(11, 7); list.add(12, 8); list.add(13, 34); list.add(14, 33); list.add(15, 22); list.add(16, 35); List<Integer> listD = new ArrayList<>(); /* listD.add(0, 5); listD.add(1, 2); listD.add(2, 1);*/ listD.add(0, 1); listD.add(1, 2); listD.add(2, 1); System.out.println("快速排序:"); System.out.println("排序前:"); for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i) + " "); } System.out.println(); quickSort(list,0,list.size()-1); System.out.println("排序后:"); for (int i = 0; i < list.size(); i++) { System.out.print(list.get(i) + " "); } } }