0%

排序

排序

折半插入排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
using namespace std;

void BInsertSort(int A[], int n){
int low, mid, high;
int i,j,t;
for(i=1; i<n; i++){
t = A[i];
low = 0;
high = i-1;
while(low<=high){
mid = (low+high)/2;
if(A[mid]>t)
high = mid-1;
else
low = mid+1;
}
for(j=i-1; j>=high; j--)
A[j+1] = A[j];
A[high+1] = t;
}
}

int main(){
int a[100];
int n;
while(cin>>n){
for(int i=0; i<n; i++)
cin>>a[i];
BInsertSort(a,n);
for(int i=0; i<n; i++)
cout<<a[i]<<" ";
cout<<endl;
}

return 0;
}

希尔排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;

void Shellsort(int A[],int n){
int i,j,dk; //dk是增量
int tmp;
for(dk=n/2; dk>0; dk/=2)
for(i=dk; i<n; i++){
tmp = A[i];
for(j=i; j>=dk; j-=dk)
if(tmp<A[j-dk])
A[j] = A[j-dk];
else
break;
A[j] = tmp;
}
}
int main(){
int n,i;
int a[100];
while(cin>>n){
for(i=0; i<n; i++)
cin>>a[i];
Shellsort(a,n);
for(i=0; i<n; i++)
cout<<a[i]<<" ";
cout<<endl;
}
return 0;
}

快速排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<bits\stdc++.h>
using namespace std;

//可以三数取中取枢纽
int partition(int A[], int low, int high){
int pivot = A[low]; //枢纽
while(low<high){
while(low<high&&A[high]>=pivot) //找到大于pivot的值
high--;
A[low] = A[high];
while(low<high&&A[low]<=pivot)
low++;
A[high] = A[low];
}
A[low] = pivot;
return low;
}
void Qsort(int A[], int low, int high){
if(low<high){
int pivot = partition(A,low,high);
Qsort(A,low,pivot-1);
Qsort(A,pivot+1,high);
}
}
int main(){
int A[100];
int n,i;
while(cin>>n){
for(i=0; i<n; i++)
cin>>A[i];
Qsort(A,0,n-1);
for(i=0; i<n; i++)
cout<<A[i]<<" ";
cout<<endl;
}
return 0;
}