赞
踩
//形参:数组地址,数组元素个数 void InsertSort(int *a, int size) { int i, j, tmp; for (i = 1; i < size; i++) { tmp = a[i]; for (j = i - 1; j >= 0; j--) { if (tmp < a[j]) { a[j + 1] = a[j]; //a[i] 被a[j]覆盖 count++; } else { break; } } a[j + 1] = tmp; } }
//形参:数组地址,数组元素个数 void ShellSort(int *a, int size) { int i, j, tmp, h; for (h = size / 2; h > 0; h /= 2) { for (i = h; i < size; i++) { tmp = a[i]; for (j = i - h; j >= 0; j -= h) { if (tmp < a[j]) { a[j + h] = a[j]; } else { break; } } a[j + h] = tmp; } } }
//形参:数组地址,数组元素个数 void BubbleSort(int *a, int size) { int i, j, tmp; for (i = 0; i < size - 1; i++) { for (j = 0; j < size - i - 1; j++) { if (a[j] > a[j + 1]) { tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } }
//形参:1、数组地址 2、数组第一个元素下标 2、数组最后一个元素下标 void QuickSort(int *a, int low, int high) { if (low >= high) { return ; } int x = low; int y = high; int Index = a[x]; while (x < y) { while(x < y && a[y] > Index) { y--; } if (x < y) { a[x++] = a[y]; } while (x < y && a[x] < Index) { x++; } if (x < y) { a[y--] = a[x]; } } a[x] = Index; QuickSort(a, low, x - 1); QuickSort(a, x + 1, high); }
//形参:数组地址,数组元素个数 void SelectSort(int *a, int size) { int i, j, tmp; int minIndex = 0; for (i = 0; i < size - 1; i++) { minIndex = i; for (j = i + 1; j < size; j++) { if (a[minIndex] > a[j]) { minIndex = j; } } tmp = a[minIndex]; a[minIndex] = a[i]; a[i] = tmp; } }
//形参:数组地址,根节点,最后节点下标 void AdjustHeap(int *a, int root, int last) { int child = 2 * root + 1; int tmp = a[root]; while(child <= last) { if (child + 1 <= last && a[child] < a[child + 1]) { child++; } if (a[child] > tmp) { a[root] = a[child]; } else { break; } root = child; child = 2 * child + 1; } a[root] = tmp; } //形参:数组地址,数组元素个数 void HeapSort(int *a, int len) { int i, tmp; for(i = len / 2 -1; i >= 0; i--) { AdjustHeap(a, i, len - 1); } for (i = len - 1; i > 0; i--) { tmp = a[0]; a[0] = a[i]; a[i] = tmp; AdjustHeap(a, 0, i - 1); } }
//合并两个已经排好序的数组:a[start,...,middle]和 a[middle+1,...,end] void Merge(int *a, int start, int middle, int end) { if (NULL == a) { return; } int len = end - start + 1; int i = start; int j = middle + 1; int *tmp = (int *)malloc(sizeof(int)*len); int Index = 0; while(i <= middle && j <= end) { tmp[Index++] = (a[i] <= a[j] ? a[i++] : a[j++]); } while(i <= middle) { tmp[Index++] = a[i++]; } while(j <= end) { tmp[Index++] = a[j++]; } Index = 0; while (Index < len) { a[start++] = tmp[Index++]; } free(tmp); } //形参:数组地址,第一个元素下标,最后一个元素下标 a[start,...end] void MergeSort(int *a, int start, int end) { int middle; if (NULL == a) { return; } if (start < end) //只有一个元素不执行 { middle = (start + end) / 2; //中间元素下标 sort(a, start, middle); //前半部分继续调用 sort(a, middle + 1, end); //后半部分继续调用 Merge(a, start, middle, end); //合并拆分的两个部分 } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。