排序-冒泡,快速(选择排序)

    xiaoxiao2021-03-25  81

    // // main.cpp // Sort // // Created by Bazinga on 2017/3/9. // Copyright © 2017年 Bazinga. All rights reserved. // #include <iostream> using namespace std; void BubSort(int * a , int n){ for(int i=0 ; i< n-1 ; i++){ for (int j=0; j < n-i-1; j++) { if(a[j]<a[j+1]){ int temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; } } } } void printSort(int * a ,int n){ for (int i = 0; i < n; i++) { cout<<a[i]<<" "; } cout<<endl; } void swap(int a[],int low, int high){ a[low] = a[low] + a[high]; a[high] = a[low] - a[high]; a[low] = a[low] - a[high]; } //返回的是中轴点的坐标 //temp为中轴点 int QuickSort_Once(int a[] , int low , int high){ int i,j,temp; i = low; j = high; //优化保证选择首尾中的数处于三个数的中间大小 int m = low + (high - low) / 2 ;//数组中间元素的下标 if (a[low]>a[high]) //找到首尾较小的 swap(a, low, high); if (a[m] > a[high]) //找到中尾较小的 swap(a, high, m); if (a[m] > a[low]) //保证左端最小 swap(a, m, low); temp = a[i]; while(i!=j){ while(a[j]>=temp && i<j) j--; a[i] = a[j]; while(i<j && a[i]<=temp ) i++; a[j] = a[i]; } //i,j指针相遇,即为中轴点的值 a[i] = temp; return i; } //j指针先走,只要在没遇到i指针就停下来,那么它一定比基准数小 int QuicjSort_Once1(int a[],int low ,int high){ int i = low; int j = high; int mid = (low + high ) / 2; if(a[i]>a[j]) swap(a, i , j); if (a[mid] > a[high] ) { swap(a, mid, high ); } if (a[low] < a[mid]) { swap(a, low , mid); } int temp = a[low]; while(i!=j){ while(a[j] >= temp && i<j) j--; while (a[i] <= temp && i<j) i++; if (i!=j) { int swap1 = a[i]; a[i] = a[j]; a[j] = swap1; } } a[low] = a[i]; a[i] = temp; return i ; } void QuackSort(int a[] , int low , int high){ if(low <= high - 1) //长度>1 { int center = QuicjSort_Once1(a, low, high); // cout<<center<<endl; QuackSort(a, low, center-1); QuackSort(a, center+1, high); } } int main(int argc, const char * argv[]) { int a[100] , n ; cin>>n; for(int i =0 ;i<n ; i++){ cin>>a[i]; } printf("冒泡排序:\n"); BubSort(a,10); printSort(a, 10); printf("快速排序:\n"); QuackSort(a, 0, 9); printSort(a, 10); return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-32520.html

    最新回复(0)