快速排序之C++实现
一、源代码:QuickSort.cpp
1 #include<iostream> 2 using namespace std; 3 /*定义输出一维数组的函数*/ 4 void print(int array[], int n) 5 { 6 for (int i = 0; i < n; i++) 7 { 8 cout << array[i] << " "; 9 } 10 cout << endl; 11 } 12 13 //选择基准(轴) 14 int partition(int array[], int low, int high) 15 { 16 while (low < high) 17 { 18 //low位置为轴点,low右边的不小于low左边的 19 while (low < high&&array[low] <= array[high]) 20 { 21 high--; 22 } 23 int temp = array[low]; 24 array[low] = array[high]; 25 array[high] = temp; 26 //high位置为轴点,high左边的不大于high右边的 27 while (low < high&&array[low] <= array[high]) 28 { 29 low++; 30 } 31 temp = array[low]; 32 array[low] = array[high]; 33 array[high] = temp; 34 } 35 return low; 36 } 37 38 void quickSortHelp(int array[], int low, int high) 39 { 40 if (low < high) 41 { 42 //找枢轴元位置 43 int location = partition(array, low, high); 44 //递归调用 45 quickSortHelp(array, low, location - 1); 46 quickSortHelp(array, location + 1, high); 47 } 48 } 49 50 void quickSort(int array[], int n) 51 { 52 //以第一个数组元素为基准(轴) 53 quickSortHelp(array, 0, n - 1); 54 } 55 56 int main() 57 { 58 //定义待排序的一维数组 59 int array[] = { 1, 3, 4, 5, 2, 6, 10, 9, 8, 7 }; 60 //输出原始数组 61 cout << "原始数组是:" << endl; 62 print(array, 10); 63 //对数组进行排序 64 quickSort(array, 10); 65 //输出排序后的数组 66 cout << "排序后的数组是:" << endl; 67 print(array, 10); 68 return 0; 69 }
二、运行效果
原文:http://www.cnblogs.com/zfc-java/p/7392482.html