必须知道的C语言八大排序算法(收藏)

2020-01-06 17:55:59刘景俊

2.传统冒泡排序中每一趟排序操作只能找到一个最大值或最小值,我们考虑利用在每趟排序中进行正向和反向两遍冒泡的方法一次可以得到两个最终值(最大者和最小者) , 从而使排序趟数几乎减少了一半。

改进后的算法实现为:


void Bubble_2 ( int r[], int n){ 
 int low = 0; 
 int high= n -1; //设置变量的初始值 
 int tmp,j; 
 while (low < high) { 
 for (j= low; j< high; ++j) //正向冒泡,找到最大者 
 if (r[j]> r[j+1]) { 
 tmp = r[j]; r[j]=r[j+1];r[j+1]=tmp; 
 } 
 --high;  //修改high值, 前移一位 
 for ( j=high; j>low; --j) //反向冒泡,找到最小者 
 if (r[j]<r[j-1]) { 
 tmp = r[j]; r[j]=r[j-1];r[j-1]=tmp; 
 } 
 ++low;  //修改low值,后移一位 
 } 
} 

6. 交换排序—快速排序(Quick Sort)

基本思想:

1)选择一个基准元素,通常选择第一个元素或者最后一个元素,

2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。

3)此时基准元素在其排好序后的正确位置

4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。

快速排序的示例:

(a)一趟排序的过程:

c语言,八大排序算法,c语言排序算法

(b)排序的全过程

c语言,八大排序算法,c语言排序算法

算法的实现:

递归实现:


void print(int a[], int n){ 
 for(int j= 0; j<n; j++){ 
 cout<<a[j] <<" "; 
 } 
 cout<<endl; 
} 
void swap(int *a, int *b) 
{ 
 int tmp = *a; 
 *a = *b; 
 *b = tmp; 
} 
int partition(int a[], int low, int high) 
{ 
 int privotKey = a[low];  //基准元素 
 while(low < high){   //从表的两端交替地向中间扫描 
 while(low < high && a[high] >= privotKey) --high; //从high 所指位置向前搜索,至多到low+1 位置。将比基准元素小的交换到低端 
 swap(&a[low], &a[high]); 
 while(low < high && a[low] <= privotKey ) ++low; 
 swap(&a[low], &a[high]); 
 } 
 print(a,10); 
 return low; 
} 
void quickSort(int a[], int low, int high){ 
 if(low < high){ 
 int privotLoc = partition(a, low, high); //将表一分为二 
 quickSort(a, low, privotLoc -1); //递归对低子表递归排序 
 quickSort(a, privotLoc + 1, high); //递归对高子表递归排序 
 } 
} 
int main(){ 
 int a[10] = {3,1,5,7,2,4,9,6,10,8}; 
 cout<<"初始值:"; 
 print(a,10); 
 quickSort(a,0,9); 
 cout<<"结果:"; 
 print(a,10); 
}