双向冒泡
//双向冒泡 void DoubleBubble(ElemType A[], int n) { int i,temp; int low = 0, high = n - 1; int flag = 1;//一次冒泡后记录元素是否交换标志 while (low < high&&flag) {//循环跳出条件中当flag=0时说明已没有逆序 flag = 0; for(i=low;i<high;i++) if (A[i] > A[i + 1]) { temp = A[i+1]; A[i + 1] = A[i]; A[i] = temp; flag = 1; } high--; for(i=high;i>low;i--) if (A[i] < A[i - 1]) { temp = A[i - 1]; A[i - 1] = A[i]; A[i] = temp; flag = 1; } low++; } } //把所有奇数移到偶数前,先从前向后找到一个偶数元素,再从后向前找到一个奇数元素 void move(ElemType A[], int len) { int temp; int i = 0, j = len - 1; while (i < j) { while (i < j && A[i] % 2 != 0) i++; while (i < j && A[j] % 2 != 1) j--; if (i < j) { temp = A[i]; A[i] = A[j]; A[j] = temp; i++; j--; } } } //随机求出枢轴的下标,然后将枢轴值与A[low]交换 int Partition(ElemType A[], int low, int high) { int rand_Index = low + rand() % (high - low + 1); swap(A[rand_Index],A[low]); ElemType pivot = A[low]; int i = low; for (int j = low + 1; j <=high; j++) if (A[j] < pivot) swap(A[++i], A[j]); swap(A[i], A[low]); return i; } //找出第k小的元素 int Mink(int A[], int low, int high, int k) { int pivot = A[low]; int low_temp = low; int high_temp = high; while (low < high) { while (low<high && A[high]>=pivot) --high; A[low] = A[high]; while (low < high && A[low] <= pivot) ++low; A[high] = A[low]; } A[low] = pivot; if (low == k) return A[low]; else if (low > k) return Mink(A, low_temp, low - 1, k); else return Mink(A, low + 1, high_temp, k); } int SetPartition(int A[], int n) { int pivotkey, low = 0, low0 = 0, high = n - 1, high0 = n - 1, flag = 1, k = n / 2, i; int s1 = 0, s2 = 0; while (flag) { pivotkey = A[low]; while (low < high) { while (low < high && A[high] >= pivotkey) --high; if (low != high) A[low] = A[high]; while (low < high && A[low] <= pivotkey) ++low; if (low != high) A[high] = A[low]; } A[low] = pivotkey; if (low == k - 1) flag = 0; else { if (low < k - 1) { low0 = ++low; high = high0; } else { high0 = --high; low = low0; } } } for (i = 0; i < k; i++) s1 += A[i]; for (i = k; i < n; i++) s2 += A[i]; return s2 - s1; } typedef enum{RED,WHITE,BLUE} color; void Flag_Arrange(color A[], int n) { int i = 0, j = 0, k = n - 1; while(j<=k) switch (A[j]) { case RED: swap(A[i], A[j]); i++; j++; break; case WHITE: j++; break; case BLUE:swap(a[j], a[k]); k--; } }
努力的意义就是放眼望去以后都是喜欢的人和事......