intmain() { int n;//元素个数 int m;//输入元素大小 cin >> n; vector<int> a;//动态数组 for (int i = 0; i < n; i++) { cin >> m; a.push_back(m); } //选择排序, for (int i = 0; i < a.size()-1; i++) { int min = i; for (int j = i+1; j < a.size(); j++) { if (a[j] < a[min]) min = j;//记录目前能找到的最小值元素的下标 }
//2路归并排序 voidmerge(int a[], int L1, int R1, int L2, int R2) { int i = L1; int j = L2; int temp[maxn], index = 0; while (i <= R1 && j <= R2) { if (a[i] <= a[j]) { temp[index++] = a[i++]; } else { temp[index++] = a[j++]; } } while (i <= R1) { temp[index++] = a[i++]; } while (j <= R2) { temp[index++] = a[j++]; } //合并后的序列赋值回数组a for (int i = 0; i < index; i++) a[i + L1] = temp[i]; }
voidmergesort(int a[], int left, int right){ if (left < right) { int mid = (left + right) / 2; mergesort(a, left, mid); mergesort(a, mid + 1, right); merge(a, left, mid, mid + 1, right);//两个有序的子区间合并 } }
intmain() { int n;//元素个数 //int m;//输入元素大小 cin >> n; //vector<int> a;//动态数组 int a[maxn]; for (int i = 0; i < n; i++) { cin >> a[i]; //a.push_back(m); } mergesort(a, 0, n - 1);
for (int i = 0; i < n; i++) { cout << a[i] << endl; } return0;
/* int partition(int a[], int left, int right) { int temp = a[left]; while (left < right) { while (left < right && temp < a[right]) right--; a[left] = a[right]; while (left < right && temp >= a[left]) left++; a[right] = a[left]; } a[left] = temp; return left; } */
//2路归并排序 voidmerge(int a[], int L1, int R1, int L2, int R2) { int i = L1; int j = L2; int temp[maxn], index = 0; while (i <= R1 && j <= R2) { if (a[i] <= a[j]) { temp[index++] = a[i++]; } else { temp[index++] = a[j++]; } } while (i <= R1) { temp[index++] = a[i++]; } while (j < R2) { temp[index++] = a[j++]; } //合并后的序列赋值回数组a for (int i = 0; i < index; i++) a[i + L1] = temp[i]; }
voidmergesort(int a[], int left, int right){ if (left < right) { int mid = (left + right) / 2; mergesort(a, left, mid); mergesort(a, mid + 1, right); merge(a, left, mid, mid + 1, right);//两个有序的子区间合并 } }
intmain() { int n;//元素个数 //int m;//输入元素大小 cin >> n; //vector<int> a;//动态数组 int a[maxn]; for (int i = 0; i < n; i++) { cin >> a[i]; //a.push_back(m); } mergesort(a, 0, n - 1);
for (int i = 0; i < n; i++) { cout << a[i] << endl; } return0;