归并排序
#include<iostream>
#include<time.h>
using namespace std;
const int MaxSize = 50;
归并排序
void Merge(int * num, int left, int mid, int right) {
int * buf = new int[right - left + 1];
int l1 = left, l2 = mid + 1;
int r1 = mid, r2 = right, cnt = 0;
while (l1 <= r1 && l2 <= r2) {
if (num[l1] < num[l2]) {
buf[cnt++] = num[l1++];
}
else {
buf[cnt++] = num[l2++];
}
}
while (l1 <= r1) buf[cnt++] = num[l1++];
while (l2 <= r2) buf[cnt++] = num[l2++];
for (int i = 0; i < cnt; i++) {
num[left + i] = buf[i];
}
delete[] buf;
}
void MergeSort(int * num, int left, int right) {
//递归结束条件
if (left == right) return;
int mid = (left + right) / 2;
MergeSort(num, left, mid);
MergeSort(num, mid + 1, right);
Merge(num, left, mid, right);
}
int main() {
int num[MaxSize];
for (int i = 0; i < MaxSize; i++) num[i] = rand() % 250;
MergeSort(num, 0, MaxSize-1);
for (int i = 0; i < MaxSize; i++) cout << num[i] << " ";
}
/*clock_t start, end;
start = clock();
end = clock();
printf("time used: %lf\n", (double)(end - start) / CLOCKS_PER_SEC);*/
java归并排序
import java.util.Random;
public class Main {
public static void main(String[] args) {
int MaxSize = 100;
int num[] = new int[MaxSize];
for (int i = 0; i < MaxSize; i++) num[i] = new Random().nextInt(250);
MergeSort(num, 0, MaxSize-1);
for (int i = 0; i < MaxSize; i++) System.out.print(num[i] + " ");
}
private static void Merge(int[] num, int left, int mid, int right) {
int l1 = left;
int r1 = mid;
int l2 = mid+1;
int r2 = right;
int[] buf = new int[right-left+1];
int cnt = 0;
while(l1 <= r1 && l2 <= r2) {
if(num[l1] < num[l2]) {
buf[cnt++] = num[l1++];
} else {
buf[cnt++] = num[l2++];
}
}
while(l1 <= r1) buf[cnt++] = num[l1++];
while(l2 <= r2) buf[cnt++] = num[l2++];
for(int i=0; i<cnt; i++) {
num[left+i] = buf[i];
}
}
private static void MergeSort(int[] num, int left, int right) {
if(left == right) return;
int mid = (left + right) / 2;
MergeSort(num, left, mid);
MergeSort(num, mid + 1, right);
Merge(num, left, mid, right);
}
}
快速排序
快速排序
void QuickSort(int * num, int left, int right) {
if (left >= right) return;
int base = num[left];
int i = left, j = right;
while (i != j) {
//此处以最左数为基准数,因此为处理已经排序好的数组应该先从右边寻找
while (i < j&&num[j] >= base) j--;
while (i < j&&num[i] <= base) i++;
if (i < j) {
swap(num[i], num[j]);
}
}
num[left] = num[i];
num[i] = base;
QuickSort(num, left, i - 1);
QuickSort(num, i + 1, right);
}
快速排序
int main() {
int num[MaxSize];
for (int i = 0; i < MaxSize; i++) num[i] = rand() % 250;
QuickSort(num, 0, MaxSize-1);
for (int i = 0; i < MaxSize; i++) cout << num[i] << " ";
}