标签:bsp 归并排序 while 数组 int stream for clu 一个
//merge sort //合并有序序列 //没有改变相等元素的前后位置 #include<iostream> #include<vector> using namespace std; void merge(vector<int>& v, int left, int right, int right_end) { int* v2 = new int[right_end - left + 1];//用()会内存泄露 int s_start = left; int start = left; int left_end = right - 1; while (left <= left_end && right <= right_end) { if (v[left] <= v[right]) { v2[s_start++] = v[left++]; //合并进临时数组(且按照排序范围的下标) } else { v2[s_start++] = v[right++]; } } while (left <= left_end) {//将某方剩余的合并进s v2[s_start++] = v[left++]; } while (right <= right_end) { v2[s_start++] = v[right++]; } for (int i = start; i <= right_end; i++) { v[i] = v2[i]; } } void msort(vector<int>& v, int left, int right) { if (left >= right) {//只剩最后一个时 return; } int mid = (left + right) / 2; msort(v, left, mid); msort(v, mid + 1, right);//排完左边排右边 //排完合并 merge(v, left, mid + 1, right);//此时用到vector s,在参数中给出左边一半的起点终点,的起点,终点 //可以不给出mid,因为右半起点-1就是左半终点 } void mergsort(vector<int>& v) { int size = v.size(); if (v.size() == 0) { return; } msort(v, 0, size - 1);//指明排序范围 } int main() { vector<int> a{ 1,5,7,4,3,8,5,1,2,99,242,241 }; mergsort(a); for (int i = 0; i < a.size(); i++) { cout << a[i] << " "; } }
标签:bsp 归并排序 while 数组 int stream for clu 一个
原文地址:https://www.cnblogs.com/ziggystardust-pop/p/12616301.html