快速排序經常在考,需要掌握,基本原理:
一趟就是左右哨兵碰頭了,即交換一次基準數。
Java實現:
package com.hwb.app;
public class QuickSort {
static void Print(int a[]){
for(int i=0; i<a.length; i++)
{
System.out.print(a[i] + (i<a.length-1 ? ", " : ""));
}
System.out.println();
}
static void Sort(int a[], int p, int q){
if(p>q)//很重要,越界判斷
return;
int key = a[p];
int i = p;
int j = q;
while( i!=j )
{//下面的是從大到小排序,如果從小到大,則需右邊找比key小的、左邊找比key大的,最後交換(當然)
//哨兵j找到比key大的停止
while( a[j]<=key && i<j )
j--;
//哨兵i找到比key小的停止
while( a[i]>=key && i<j )
i++;
if (i<j) {//兩個數交換
//方式一
int tt = a[i];
a[i] = a[j];
a[j] = tt;
//方式二
//a[i] = a[i] + a[j];
//a[j] = a[i] - a[j];
//a[i] = a[i] - a[j];
}
}
if(i==j)//將哨兵交換
{
a[p] = a[i];
a[i] = key;
}
//再排序新基準i的左邊、右邊
Sort(a,p,i-1);
Sort(a,i+1,q);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int aa[] = {9, 2, 4, 1, 3, 8, 5};
Print(aa);
Sort(aa, 0, aa.length-1);
Print(aa);
}
}
C++實現:
#pragma once
#include <iostream>
using namespace std;
void Print(int* a, int n) {
for (int i = 0; i < n; i++)
{
cout << a[i] << ((i < n-1) ? ", " : "");
}
cout<<endl;
}
//快速排序
void quick_sort(int s[], int l, int r)
{
if (l < r)
{
//Swap(s[l], s[(l + r) / 2]); //將中間的這個數和第一個數交換 參見注1
int i = l, j = r, x = s[l];
while (i < j)
{
while (i < j && s[j] >= x) // 從右向左找第一個小於x的數
j--;
if (i < j)
s[i++] = s[j];
while (i < j && s[i] < x) // 從左向右找第一個大於等於x的數
i++;
if (i < j)
s[j--] = s[i];
}
s[i] = x;
quick_sort(s, l, i - 1); // 遞歸調用
quick_sort(s, i + 1, r);
}
}
int main_QuickSort()
{
int aa[] = { 9, 2, 4, 1, 3, 8, 5 };
int n = sizeof(aa) / sizeof(aa[0]);
Print(aa, n);
quick_sort( aa, 0, n-1 );//從大到小排列
Print(aa, n);
return 0;
}
參考:
http://developer.51cto.com/art/201403/430986.htm
http://blog.csdn.net/morewindows/article/details/6684558
http://blog.csdn.net/lemon_tree12138/article/details/50622744