資料結構-陣列排序(冒泡 選擇 插入 歸併(合併有序陣列))-C語言
阿新 • • 發佈:2018-11-27
- 氣泡排序
- 選擇排序
- 插入排序
- 歸併排序(合併有序陣列)
//
// Created by 範興國 on 2017/9/24.
//
/*
*
* 陣列排序 氣泡排序 選擇排序 插入排序 二路歸併合併陣列
*
*
* */
#include <stdio.h>
#include <stdlib.h>
#define N 10
main(){
int arr[N];
int temp;
for(int i=0;i<N;i++){
arr[i]=rand()%10;
}
printf("原內容:" );
for (int k = 0; k <N ; k++) {
printf("%d\t",arr[k]);
}
printf("\n");
printf("排序後:\n");
/*
* 氣泡排序
* 輪數:陣列長度-1
* 第i論次數:陣列長度-i-1
* 呼叫 j j+1
*
* */
/*
時間複雜度分析:
Comparison and swap require time that is bounded by a constant c.
There are two nested loops in (the standard) Bubble Sort.
The outer loop runs for exactly N iterations.
But the inner loop runs get shorter and shorter:
When i=0, (N−1) iterations (of comparisons and possibly swaps),
When i=1, (N−2) iterations,
...,
When i=(N−2), 1 iteration,
When i=(N−1), 0 iteration.
Thus, the total number of iterations = (N−1)+(N−2)+...+1+0 = N*(N−1)/2
Total time = c*N*(N−1)/2 = O(N^2)
*/
// for(int i=0;i<N-1;i++){
// for (int j = 0; j <N-i-1; j++) {
// if(arr[j]>arr[j+1]){
// temp=arr[j];
// arr[j]=arr[j+1];
// arr[j+1]=temp;
// }
// }
// }
/*
選擇排序
步驟:(找到最小的元素,並前面的交換)
1.Find the position of the smallest item X, in the range of [L...N−1],
2.Swap X with the L-th item,
3.Increase the lower-bound L by 1 and repeat Step 1 until L = N-2.
時間複雜度:
Total: O(N2) — To be precise, it is similar to Bubble Sort analysis.
* */
// int min=arr[0];
// int index;
// for(int i=0;i<N-1;i++){
// min=arr[i+1];
// index=i+1;
// for (int j = i+1; j < N; j++) {
// if(min>arr[j]){
// min=arr[j];
// index=j;
// }
// }
// temp=arr[i];
// arr[i]=arr[index];
// arr[index]=temp;
// }
/*
*
* 插入排序
*
* 方式一:
*步驟:1->N遍歷,從頭開始比較,若比之大(或小)則交換
*
* */
// for(int i=1;i<N;i++){
// for (int j = 0; j < i; j++) {
// if(arr[i]<arr[j]){
// temp=arr[i];
// arr[i]=arr[j];
// arr[j]=temp;
// }
// }
// }
/*
*
* 方式二:後插入
* cp: 備份第i個
* i從後往前移
*
* 時間複雜度:
* Thus, the best-case time is O(N × 1) = O(N) and the worst-case time is O(N × N) = O(N2).
*
* */
// int cp;
// for(int i=1;i<N;i++){
// cp=arr[i];
// for(int j=i-1;j>=0&&arr[j]>cp;j--){
// arr[j+1]=arr[j];
// arr[j]=cp;
// }
// }
/*
*
* 二路歸併 之 有序數組合並
*
* a={11,13,15,17,19}
* b={2,4,6,8,20}
* c=a+b={11,13,15,17,19,2,4,6,8,20}
* 對c陣列進行排序
*
* 時間複雜度:掃描的各個陣列都只有1次,故為O(N)
*
*
* */
// int c[10]={2,4,6,8,20,11,13,15,17,19};
//
// //準備工作
// int L=0,R=5;//左起始點 右起始點
// int RightEnd=9;//右終止點
// int LeftEnd=R-1;//左終止點
// int NumElements=RightEnd-L-1;//元素總數
// int Tmp;//臨時陣列指標
// int TmpA[10];//臨時陣列
//
// //合併
// while(L<=LeftEnd&&R<=RightEnd){
// if (c[L]<=c[R]) TmpA[Tmp++]=c[L++];
// else TmpA[Tmp++]=c[R++];
// }
// while (L<=LeftEnd){
// TmpA[Tmp++]=c[L++];
// }
// while (R<=LeftEnd){
// TmpA[Tmp++]=c[R++];
// }
//
// //TmpA-->c
// for(int i=0;i<NumElements;i++,RightEnd--){
// c[RightEnd]=TmpA[RightEnd];
// }
//
// //顯示結果
// printf("歸併排序結果:");
// for(int i=0;i<10;i++){
// printf("%d\t",c[i]);
// }
printf("排序後結果:");
for (int k = 0; k <N ; k++) {
printf("%d\t",arr[k]);
}
}