标签:排序
插入排序:直接插入,希尔排序
选择排序:选择排序,堆排序
交换排序:冒泡排序,快速排序
归并排序:归并排序
#include<iostream> #include<assert.h> using namespace std; void InsertSort(int *arr, size_t size) { assert(arr); for (int i = 0; i < size - 1; ++i) { int tmp = arr[i+1]; int end = i; while (end >= 0&&arr[end]>tmp) { arr[end + 1] = arr[end]; --end; } arr[end + 1] = tmp;//即使都大于tmp,将tmp放置arr[0]处 } } void ShellSort(int *arr, size_t size) { assert(arr); int gap = size; while (gap>1)//注意跳出条件 { gap = gap / 3 + 1; for (int i = 0; i < size - gap; ++i)//i可取到size-1-gap { int tmp = arr[i + gap]; int end = i; while (end >= 0 && arr[end]>tmp) { arr[end + gap] = arr[end]; end-=gap; } arr[end + gap] = tmp;//即使都大于tmp,将tmp放置arr[0]处 } } } void SearchSort(int *arr, size_t size) { assert(arr); for (int i = 0,j=size-1; i < j; ++i,-j) { int min = i; int max = j; for (int k = i; k<=j;++k) { if (arr[min]>arr[k]) min = k; if (arr[max] < arr[k]) max = k; } if (min != i) { int temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; if (max == i) //如果最大值在最左边,肯定要被移走,此时要转移到相应的新位置 { max = min; } } if (max != j) { int tmp = arr[j]; arr[j] = arr[max]; arr[max] = tmp; } } } int Quick_Sort(int *arr, int left, int right) { assert(arr); if (left >= right) return right; int tmp = arr[right]; int index = right; --right; while (left < right) { while (left < right&&arr[left] <= tmp) left++; while (left < right&&arr[right] >=tmp) right--; if (left < right) swap(arr[left], arr[right]); } if (arr[right] >= tmp) swap(arr[right], arr[index]);//重点 return right; } void QuickSort(int* arr,int left,int right) { assert(arr); if (left < right) { int mid = Quick_Sort(arr, left, right); QuickSort(arr, left, mid-1); QuickSort(arr, mid+1, right); } } void BubbleSort(int* arr, size_t size) { assert(arr); int flag = 0; for (int i = 0; i < size - 1; ++i) { flag = 0; for (int j = 0; j < size - i - 1;++j) { if (arr[j]>arr[j + 1]) { swap(arr[j], arr[j + 1]); } flag = 1; } if (flag == 0) break; } } void Print(int *arr, size_t size) { for (int i = 0; i < size; ++i) { cout << arr[i] << " "; } cout << endl; } #include"Sort.h" void Test1() { int arr[] = { 2, 0, 4, 9, 3, 6, 8, 7, 1, 5 }; Print(arr, 10); //InsertSort(arr, 10); //ShellSort(arr, 10); //SearchSort(arr, 10); //BubbleSort(arr, 10); QuickSort(arr,0,9); Print(arr, 10); }
本文出自 “小止” 博客,请务必保留此出处http://10541556.blog.51cto.com/10531556/1754981
标签:排序
原文地址:http://10541556.blog.51cto.com/10531556/1754981