排序程序总结

来源:互联网 发布:酒店市场数据分析 编辑:程序博客网 时间:2024/06/11 04:17

1.冒泡排序

void bubble_sort(int a[],int len){for(int i=0;i<len;i++){for (int j=1;j<len-i;j++){if (a[j-1]>a[j]){int temp = a[j-1];a[j-1] = a[j];a[j] = temp;}}}}

改进:

void bubble_sort_1(int a[],int len){bool flag=true;int i=0;while (flag){flag = false;for (int j=1;j<len-i;j++){if (a[j-1]>a[j]){flag = true;int temp = a[j-1];a[j-1] = a[j];a[j] = temp;}}i++;}}
2.快速排序

int partition(int a[],int low,int high){int pviot = a[high];int i=low-1;int temp;for (int j=low;j<high;j++){if (a[j] < pviot){i++;temp = a[j];a[j] = a[i];a[i] = temp;}}temp = a[i+1];a[i+1] = a[high];a[high] = temp;return i+1;}void quick_sort(int a[],int low,int high){if (low <= high){int pos = partition(a,low,high);quick_sort(a,low,pos-1);quick_sort(a,pos+1,high);}}

3.归并排序

//------------------------merge_sort----------------------void merge(int nums[],int low,int mid,int high){int i=low,j=mid+1; //左指针,右指针int k=0;int *temp  = new int[high-low+1];while (i<=mid && j<=high){if (nums[i]<nums[j])temp[k++] = nums[i++];elsetemp[k++] = nums[j++];}while (i<=mid){temp[k++]=nums[i++];}while (j<=high){temp[k++]=nums[j++];}for (int kk=0;kk<(high-low+1);kk++){nums[kk+low] = temp[kk];}}void merge_sort(int nums[],int low,int high){int mid = (high+low)/2;if (low<high){merge_sort(nums,low,mid);merge_sort(nums,mid+1,high);merge(nums,low,mid,high);}}


4.选择排序

void selection_sort(int a[],int len){for (int i=0;i<len;i++){int lowIndex = i;for (int j=i+1;j<len;j++){if (a[j]<a[lowIndex]){lowIndex = j;}}int temp = a[i];a[i]=a[lowIndex];a[lowIndex]=temp;}}


原创粉丝点击