文件名称:归并排序&&快速排序c#源码
文件大小:3KB
文件格式:TXT
更新时间:2012-07-03 19:31:17
归并排序 快速排序
//快速排序 public void q_sort(int low, int high, int[] a) { int pivot, i, j,temp; if (low > high) return; i = low + 1; j = high; pivot=a[low]; while (i <= j) { while ((i <= high) && (a[i] <= pivot))//搜索大于枢轴的元素 { i++; } while ((j >= low) &&(a[j] > pivot) )//搜索小于枢轴的元素 { j--; } if (i < j) { temp = a[i]; a[i]=a[j]; a[j] = temp; } } if (low < j)//low为枢轴下标,j为小于枢轴元素的下标, { // 如果小于枢轴元素的元素在枢轴右边,则交换 temp=a[low]; a[low]=a[j]; a[j] = temp; } q_sort(low,j-1,a); q_sort(j + 1, high,a); } //归并排序 public void MergeSort(int low, int high, int[] a) { int mid, i, j, k; int[] b = new int[high+1]; if (low >= high) { return; } mid = (low + high) / 2; MergeSort(low,mid,a); MergeSort(mid+1,high,a); i = low; j = mid + 1; k = low; while ((i <= mid) && (j <= high)) { if (a[i] <= a[j]) { b[k] = a[i]; i++; } else { b[k]=a[j]; j++; } k++; } while (j <= high)//如果第二个中仍然有某些元素追加到新列表的子列表 { b[k] = a[j]; j++; k++; } while (i <= mid)//如果在第一个子列表中仍然有一些元素将它们追加到新类别中 { b[k] = a[i]; i++; k++; } for (int ii = low; ii <=high; ii++) { a[ii]=b[ii]; } } public void display(int[] a) { int n = a.Length; Console.WriteLine("排序后的数据:"); for (int i = 0; i < n; i++) { Console.WriteLine(a[i]); } } }