package algorithm.归并;import java.util.Arrays;public class Fenzhi {public static void main(String[] args) {int [] arr = {8,4,1,2,7,6,3,5};mergeSort(arr, 0, arr.length-1, new int[8]);System.out.println(Arrays.toString(arr));}public static void mergeSort(int [] arr, int left, int right, int [] tmp) {int mid = (right + left) /2;if(left < right) {mergeSort(arr, left, mid, tmp);mergeSort(arr, mid+1, right, tmp);merge(arr, left, mid, right, tmp);}}public static void merge(int [] arr, int left, int mid, int right, int [] tmp) {int i=left;int j=mid + 1;int n=0;while(i<=mid && j<=right) {if(arr[i] <= arr[j]) {tmp[n] = arr[i++];}else{tmp[n] = arr[j++];}n++;}while(i<=mid) {tmp[n] = arr[i];n++;i++;}while(j<=right) {tmp[n] = arr[j];n++;j++;}int tmpleft = left;n = 0;while(tmpleft <= right) {arr[tmpleft] = tmp[n];tmpleft++;n++;}}
}
二、Python✈✈✈
def merge_sort(num_list): length = len(num_list)if length <= 1:return num_listmid = length // 2left_l = merge_sort(num_list[:mid])right_l = merge_sort(num_list[mid:])p, q, temp_list = 0, 0, list()len_left, len_right = len(left_l), len(right_l)while len_left > p and len_right > q:if left_l[p] <= right_l[q]:temp_list.append(left_l[p])p += 1else:temp_list.append(right_l[q])q += 1temp_list += left_l[p:]temp_list += right_l[q:]return temp_listif __name__ == '__main__':num_list = [12,33,44,13,2,1,0,-1,10]new_list = merge_sort(num_list)for k, v in enumerate(new_list):num_list[k] = v print('num_list:',num_list)
int n, ar[20], tmp[20];void mergesort(int low, int mid, int high){int i=low;int j=high;n=low;while(i<=mid && j<= high) {if(ar[i]<=ar[j]){tmp[n++]=ar[i++];}else{tmp[n++]=ar[j++];} } while(i<=mid) {tmp[n++]=ar[i++];} while(j<=high) {tmp[n++]=ar[j++];} for(n=low;n<=high;n++){ar[n]=tmp[n];} }void merge(int low, int high) {if(low>=high) return;int mid=(low+high)/2;merge(low, mid);merge(mid+1,high);mergesort(low,mid,high);}using namespace std;int main(){cin >> n;for(int i=1;i<=n;i++) {cin >> ar[i];} merge(1, n); for(int i=1;i<=n;i++) {cout << ar[i] << " "; } }
总结
- python的排序是最简单的。
印象最深刻的就是切片语法通过【:】冒号获取前后两侧的集合。分厂方便
- c++的步骤和代码数与java很像