还是打击太深,面的太水,不然,也不会把这些老黄历再扒出来….
希望多写写能够增加熟练度~~
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
//交换
void swap(int* arr, int x, int y) {
int tmp = arr[x];
arr[x] = arr[y];
arr[y] = tmp;
}
//打印
void print(int* arr, int n) {
for (int i = 0;i < n;i++) {
cout << arr[i] << '\t';
}
}
//简单的交换排序 非正宗的冒泡排序
void BuddleSort(int* arr, int n) {
int i, j;
for (i = 0;i < n;i++) {
for (j = i + 1;j < n;j++) {
if (arr[i] > arr[j]) {
swap(arr, i, j);
}
}
}
}
//正宗的冒泡排序
void BuddleSort1(int * arr, int n) {
int i, j;
for (i = 0;i < n;i++) {
for (j = n - 2;j >= i;j--) {
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}
}
}
//冒泡排序改进
void BuddleSort2(int * arr, int n) {
int i, j;
int swap_falg = 1;
for (i = 0;i < n && swap_falg;i++) {
swap_falg = 0;
for (j = n - 2;j >= i;j--) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
swap_falg = 1;
}
}
}
}
//简单选择排序
void SelectSort(int* arr, int n) {
int i, j, min;
for (i = 0;i < n;i++) {
min = i;
for (j = i + 1;j < n;j++) {
if (arr[min] > arr[j])
min = j;
}
if (min != i) {
swap(arr, i, min);
}
}
}
//直接插入排序
void InsertSort(int* arr, int n) {
int i, j;
int tmp;
for (i = 1;i < n;i++) {
if (arr[i] < arr[i - 1]) {
tmp = arr[i];
for (j = i - 1;arr[j] > tmp;j--) {
arr[j + 1] = arr[j];
}
arr[j + 1] = tmp;
}
}
}
//希尔排序
void ShellSort(int* arr, int n) {
int i, j;
int tmp;
int increment = n;
do
{
increment = increment / 3 + 1;
for (i = increment;i < n;i++) {
if (arr[i] < arr[i - increment]) {
tmp = arr[i];
for (j = i - increment;j >= 0 && tmp < arr[j];j -= increment) {
arr[j + increment] = arr[j];
}
arr[j + increment] = tmp;
}
}
} while (increment > 1);
}
//快速排序
int Partition(int* arr, int low, int high) {
int pivokey = arr[low];
int i = 0;
while (low < high) {
while (low < high && arr[high] >= pivokey) {
high--;
}
swap(arr, low, high);
while (low < high && arr[low] <= pivokey) {
low++;
}
swap(arr, low, high);
}
return low;
}
void QuickSort(int* arr, int low, int high) {
int pivot;
if (low < high) {
pivot = Partition(arr, low, high);
QuickSort(arr, low, pivot - 1);
QuickSort(arr, pivot + 1, high);
}
}
//归并排序
//将两个有序数列a[first ... mid] 和 [mid...last]合并
void mergearray(int* a,int first,int mid,int last,int* temp){
int i = first,j = mid +1;
int m = mid,n = last;
int k = 0;
while(i <= m && j <= n){
if(a[i] <= a[j]){
temp[k++] = a[i++];
}else{
temp[k++] = a[j++];
}
}
while(i <= m){
temp[k++] = a[i++];
}
while(j <= n){
temp[k++] = a[j++];
}
for(int i=0;i<k;i++){
a[first+i] = temp[i];
}
}
void mergesort(int* a,int first,int last,int* temp){
if(first < last){
int mid = first + (last - first) / 2;
mergesort(a,first,mid,temp);
mergesort(a,mid+1,last,temp);
mergearray(a,first,mid,last,temp);
}
}
bool MerfeSort(int* a,int n){
int *p = new int[n]();
if(p == NULL){
return false;
}
mergesort(a,0,n-1,p);
delete[] p;
return true;
}
void printArray(int* arr,int n){
for(int i = 0;i< n;i ++){
cout << arr[i] << '\t';
}
}
int main(){
int a[] = {2,3,1,4,5,7,6,9,8,10};
MerfeSort(a,10);
printArray(a,10);
return 0;
}
先到这里~~