排序算法
#include<iostream>
#include<algorithm>
using namespace std;
void Insert_Sort(int arr[],int n){
int temp = 0,i,j;
for(int i = 1;i<n;i++){
if(arr[i]<arr[i-1]){
temp = arr[i];
for(j = i-1;j>=0&&arr[j]>temp;j--){
arr[j+1] = arr[j];
}
arr[j+1] = temp;
}
}
}
void Insert02_Sort(int arr[],int n){
int i,j,temp,low,high,mid;
for(i = 1;i<n;i++){
temp = arr[i];
low = 0;
high = i-1;
while(low<=high){
mid = (low+high)/2;
if(arr[mid]>temp){
high = mid-1;
}else{
low = mid+1;
}
}
for(j = i-1;j>=low;j--){
arr[j+1] = arr[j];
}
arr[low] = temp;
}
}
void ShellSor(int arr[],int n){
int d,i,j;
for(d = n/2;d>=1;d = d/2){
for(i = d+1;i<=n;i++){
if(arr[i]<arr[i-d]){
arr[0] = arr[i];
for(j = i-d;j>0&&arr[0]<arr[j];j-=d){
arr[j+d] = arr[j];
}
arr[j+d] = arr[0];
}
}
}
}
void BubbleSort(int arr[],int n){
for(int i = 0;i<n-1;i++){
bool tag = false;
for(int j = n-1;j>i;j--){
if(arr[j]<arr[j-1]){
swap(arr[j],arr[j-1]);
tag = true;
}
}
if(tag == false) return;
}
}
int Temptition(int arr[],int low,int high){
int temp = arr[low];
while(low<high){
while(low<high&&arr[high]>=temp){
high--;
}
arr[low] = arr[high];
while(low<high&&arr[low]<=temp){
low++;
}
arr[high] = arr[low];
}
arr[low] = temp;
return low;
}
void QuickSort(int arr[],int low,int high){
if(low<high){
int temp = Temptition(arr,low,high);
QuickSort(arr,low,temp-1);
QuickSort(arr,temp+1,high);
}
}
void SelectSort(int arr[],int n){
for(int i = 0;i<n-1;i++){
int min = i;
for(int j = i+1;j<n;j++){
if(arr[j]<arr[min]){
min = j;
}
}
if(min!=i){
swap(arr[i],arr[min]);
}
}
}
void HeadAdjust(int arr[],int k,int len){
arr[0] = arr[k];
for(int i = 2*k;i<=len;i=i*2){
if(i<len&&arr[i]<arr[i+1]){
i++;
}
if(arr[0]>=arr[i]) break;
else{
arr[k] = arr[i];
k = i;
}
}
arr[k] = arr[0];
}
void BuildMaxHeap(int arr[],int len){
for(int i = len/2;i>0;i--){
HeadAdjust(arr,i,len);
}
}
void HeapSort(int arr[],int len){
BuildMaxHeap(arr,len);
for(int i = len;i>1;i--){
swap(arr[i],arr[1]);
HeadAdjust(arr,1,i-1);
}
}
int n = 10;
int *arr02 = new int [n];
void Merge(int arr[],int low,int mid,int high){
int i,j,k;
for(k = low;k<=high;k++){
arr02[k] = arr[k];
}
for(i = low,j = mid+1,k = i;i<=mid&&j<=high;k++){
if(arr02[i]<=arr02[j]){
arr[k] = arr02[i++];
}else{
arr[k] = arr02[j++];
}
}
while(i<=mid){
arr[k++] = arr02[i++];
}
while(j<=high){
arr[k++] = arr02[j++];
}
}
void MergeSort(int arr[],int low,int high){
if(low<high){
int mid = (low+high)/2;
MergeSort(arr,low,mid);
MergeSort(arr,mid+1,high);
Merge(arr,low,mid,high);
}
}
int main(){
int arr[10] = {3,5,7,1,2,8,6,10,9,4};
HeapSort(arr,10);
SelectSort(arr,10);
QuickSort(arr,0,9);
Insert_Sort(arr,10);
ShellSor(arr,10);
for(int i = 0;i<10;i++){
cout<<arr[i]<<endl;
}
return 0;
}