归并排序vs归并排序

来源:互联网 发布:拳皇13知乎 编辑:程序博客网 时间:2024/06/06 03:54

思路:

利用递归,用临时数组保存中间子排序段,再将子排序段归并到原数组,依次递归。

 

#include<stdlib.h>int temp[100];void Merge(int* a, int low, int high ){int mid, i, j, k; mid = (low + high) / 2;for(i = low,j = mid + 1, k = 0; i <= mid && j <= high; k++){if(a[i] <= a[j]){temp[k] = a[i];i++;}else{temp[k] = a[j];j++;}}for(; i <= mid; i++){temp[k++] = a[i];}for(; j <= high; j++){temp[k++] = a[j];}for(i = 0; i < high - low + 1; i++){a[low+i] = temp[i];}}void MergeSort(int* a, int low, int high ){if(low < high){int mid = (low + high) / 2;MergeSort(a, low, mid); MergeSort(a, mid + 1, high);Merge(a, low, high);} }int main(){int a[7] = {2,5,3,6,1,9,8};MergeSort(a, 0, 7);int i;for(i = 0; i < 7; i++){printf("%d\n",a[i]);}}


 

package study;public class QuickSort {public int sort(int[] a,int low,int high){int temp = a[low];while(low <= high){while(low <= high && a[high] >= temp){high--;}a[low] = a[high];while(low <= high && a[low] <= temp){low++;}a[high] = a[low];}a[low] = temp;return low;}public void  quickSort(int[] a, int low, int high){if(low < high){int mid = sort(a, low, high);quickSort(a, low, mid - 1);quickSort(a, mid + 1, high);}}public static void main(String[] args) {int[] a = {2,3,1,7,9};QuickSort q = new QuickSort();q.quickSort(a,0,a.length-1);for(int i = a.length-1; i >=0; i--){System.out.println(a[i]);}}}


原创粉丝点击