快速排序
2014-01-24 00:00
197 查看
原理:从后往前找小的,从前往后找大的。
http://www.cnblogs.com/morewindows/archive/2011/08/13/2137415.html [2].
http://blog.sina.com.cn/s/blog_5c5bc9070100y4zv.html [3].
http://www.slyar.com/blog/c-quicksort.html
package com.duapp.itfanr; public class Test { public static void main(String args[]) { int [] a = {10,7,3,2,5,0,6,9} ; quickSort(a , 0, a.length-1 ) ; for(int i:a) System.out.println(i) ; } static void quickSort(int a[], int start, int end) { int i, j; i = start; j = end; if ((a == null) || (a.length == 0)) return; while (i < j) { while (i < j && a[i] <= a[j]) // 以数组start下标的数据为key,右侧扫描 j--; if (i < j) { // 右侧扫描,找出第一个比key小的,交换位置 int temp = a[i]; a[i] = a[j]; a[j] = temp; } while (i < j && a[i] < a[j]) // 左侧扫描(此时a[j]中存储着key值) i++; if (i < j) { // 找出第一个比key大的,交换位置 int temp = a[i]; a[i] = a[j]; a[j] = temp; } } if (i - start > 1) { // 递归调用,把key前面的完成排序 quickSort(a, 0, i - 1); } if (end - j > 1) { quickSort(a, j + 1, end); // 递归调用,把key后面的完成排序 } } }
#include<iostream> using namespace std; void quickSort(int a[],int,int); int main() { int array[]={34,65,12,43,67,5,78,10,3,70},k; int len=sizeof(array)/sizeof(int); cout<<"The orginal array are:"<<endl; for(k=0;k<len;k++) cout<<array[k]<<","; cout<<endl; quickSort(array,0,len-1); cout<<"The sorted array are:"<<endl; for(k=0;k<len;k++) cout<<array[k]<<","; cout<<endl; system("pause"); return 0; } void quickSort(int s[], int l, int r) { if (l < r) { 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; quickSort(s, l, i - 1); // 递归调用 quickSort(s, i + 1, r); } }参考: [1].
http://www.cnblogs.com/morewindows/archive/2011/08/13/2137415.html [2].
http://blog.sina.com.cn/s/blog_5c5bc9070100y4zv.html [3].
http://www.slyar.com/blog/c-quicksort.html