#include<stdio.h>
#include<stdlib.h>
//冒泡排序從小到大 第一趟得到最大的存到數組的最後,第二趟得到數組的第二大的,存到數組的倒數第二位。依次。。
void bubble_sort(int *p){
int length=6 ;
for(int i=0;i<length;i++){
for(int j=0;j<length-i;j++){
if(p[j]>p[j+1]){
int t;
t=p[j];
p[j]=p[j+1];
p[j+1]=t;
}
}
}
//打印輸出
for(int i=0;i<length;i++){
printf("%d\n",p[i]);
}
}
//希爾排序
void shell(int * p){
int length=6;
//取增量
int step=length/2;
while(step>=1){
//無序序列
for(int i=step;i<length;i++){
int temp=p[i];
int j;
//有序序列
for(j=i-step;j>=0 && temp<p[j];j=j-step){
p[j+step]=p[j];
}
p[j+step]=temp;
}
step=step/2;
}
}
//選擇排序(選擇出最小的假定第一個爲最小的 然後判斷 是否交換)
void selection_sort(int *p){
int length=6;
int min,j,i,t;
for(i=0; i<length;i++){
for(min=i,j=i+1;j<length;j++){
if(p[min]>p[j]){
min=j;
}
}
if(min!=i){
t=p[i];
p[i]=p[min];
p[min]=t;
}
}
//打印輸出
for(int i=0;i<length;i++){
printf("%d\n",p[i]);
}
}
//確定第一個數組元素的最終位置
int find_pos(int *a,int low,int high){
int val=a[low];
while(low<high){
while(low<high && a[high]>=val)
--high;
a[low]=a[high];
while(low<high && a[low]<=val)
++low;
a[high]=val;
}
a[low]=val;
return low;
}
//快速排序 遞歸調用
void quick_sort(int *a ,int low ,int high){
int pos;
if(low<high){
pos=find_pos(a,low,high);
quick_sort(a,low,pos-1);
quick_sort(a,pos+1,high);
}
}
//數組的兩兩合併操作,歸併操作
void merge(int *p,int *temp,int left,int middle,int right){
//左指針尾
int leftend=middle-1;
//右指針頭
int rightstart=middle;
//臨時數組的下標
int tempindex=left;
//數組合並後的長度
int templength=right-left+1;
//先循環兩個區間段都沒有結束的情況
while((left<=leftend)&&(rightstart<=right)){
//r如果發現有序列小的,則將此數放入臨時數組
if(p[left]<p[rightstart]){
temp[tempindex++]=p[left++];
}else{
temp[tempindex++]=p[rightstart++];
}
}
//判斷左邊序列是否結束
while(left<=leftend){
temp[tempindex++]=p[left++];
}
//判斷右邊序列是否結束
while(rightstart<=right){
temp[tempindex++]=p[rightstart++];
}
//交換數據
for(int i=0; i<templength;i++){
p[right]=temp[right];
right--;
}
}
//歸併排序 ---數組的劃分
void merge_sort(int *p ,int *temp,int left,int right){
if(left<right){
//取分割位置
int middle=(left+middle)/2;
//遞歸劃分數組左序列
merge_sort(p,temp,left,middle);
//遞歸劃分數組右序列
merge_sort(p,temp,middle+1,right);
//數組的合併操作
merge(p,temp,left,middle+1,right);
}
}
//插入排序
void insert_sort(int *a){
int len=6;
int i, j, temp;
for(i = 1; i < len; i ++)
{
temp = a[i];
for(j = i - 1; j >= 0; j --)
{
if(a[j] > temp)
{
a[j + 1] = a[j];
}else
{
break;
}
}
a[j + 1] = temp;
}
}
int main(int argc, char* argv[])
{
int a;
int b[]={35,67,23,12,65,99};
//bubble_sort(b);
//selection_sort(b);
//quick_sort(b,0,5);
shell(b);
//insert_sort(b);
for(int i=0;i<6;i++){
printf("%d\n",b[i]);
}
scanf("%a",&a);
return 0;
}
幾種常見的排序C實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.