1. 程式人生 > >(排序法) Merge Sort

(排序法) Merge Sort

sin int AS pre color pri nta pac ()

Code:

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <vector>
 5 
 6 using namespace std;
 7 const int Max = 1000;
 8 
 9 void merge(vector<int>& Array, int front, int mid, int end)
10 {
11     vector<int> LeftSub(Array.begin() + front, Array.begin() + mid + 1
); 12 vector<int> RightSub(Array.begin() + mid + 1, Array.begin() + end + 1); 13 14 LeftSub.insert(LeftSub.end(), Max); 15 RightSub.insert(RightSub.end(), Max); 16 17 int idxLeft = 0, idxRight = 0; 18 19 for (int i = front; i <= end; i++) { 20 21 if (LeftSub[idxLeft] <= RightSub[idxRight]) {
22 Array[i] = LeftSub[idxLeft]; 23 idxLeft++; 24 } 25 else{ 26 Array[i] = RightSub[idxRight]; 27 idxRight++; 28 } 29 } 30 } 31 32 33 void MergeSort(vector<int> & array, int front, int end) 34 { 35 if (front < end)
36 { 37 int mid = (front + end) / 2; 38 MergeSort(array, front, mid); 39 MergeSort(array, mid + 1, end); 40 merge(array, front, mid, end); 41 } 42 } 43 44 void PrintArray(std::vector<int> &array){ 45 for (int i = 0; i < array.size(); i++) { 46 std::cout << array[i] << " "; 47 } 48 std::cout << std::endl; 49 } 50 51 52 int main() 53 { 54 int arr[] = { 5, 3, 8, 6, 2, 7, 1, 4 }; 55 vector<int> array(arr, arr + sizeof(arr) / sizeof(int)); 56 cout << "original:" << endl; 57 PrintArray(array); 58 MergeSort(array, 0, 7); 59 std::cout << "sorted:" << endl; 60 PrintArray(array); 61 system("pause"); 62 return 0; 63 }

(排序法) Merge Sort