首頁  >  文章  >  後端開發  >  使用冒泡排序演算法對給定的數字列表進行升序排序的C程序

使用冒泡排序演算法對給定的數字列表進行升序排序的C程序

王林
王林轉載
2023-09-23 13:01:021120瀏覽

使用冒泡排序演算法對給定的數字列表進行升序排序的C程序

在 C 程式語言中,冒泡排序是最簡單的排序技術,也稱為交換排序。

冒泡排序過程

  • 將第一個元素與清單中的其餘元素進行比較,如果它們不按順序交換(交換)。

  • 對列表中的其他元素重複相同的操作列表,直到所有元素都已排序。

演算法

下面給出的是演算法,透過使用冒泡排序技術-

第1 步 - 開始

第2 步驟 - 取得清單(陣列),num

第3 步驟− readlist(list,num)

第4 步驟− printlist(list,num)

第5步 - bub_sort(list,num)

#步驟6 - printlist(list,num)

readlist (list, num)

第7步 − 停止

1. for j = 0 to num
2. read list[j].

列印列表(列表,數字)

1. for j =0 to num
2. write list[j].

bub_sort(列表,數字)

1. for i = 0 to num
2. for j =0 to (num – i)
3. if( list[j] > list[j+1])
4. swapList( address of list[j], address of list[j+1])

swapList( list[j]的位址, list[j 1]的位址)

1. temp = value at list[j]
2. value at list[j] = value at list[j+1]
3. value at list[j+1] = temp

範例

#以下是用冒泡排序技術對給定數字列表進行升序排序的C程式

 演示

#include <stdio.h>
#define MAX 10
void swapList(int *m,int *n){
   int temp;
   temp = *m;
   *m = *n;
   *n = temp;
}
/* Function for Bubble Sort */
void bub_sort(int list[], int n){
   int i,j;
   for(i=0;i<(n-1);i++)
      for(j=0;j<(n-(i+1));j++)
         if(list[j] > list[j+1])
            swapList(&list[j],&list[j+1]);
   }
   void readlist(int list[],int n){
   int j;
   printf("</p><p>Enter the elements: </p><p>");
   for(j=0;j<n;j++)
      scanf("%d",&list[j]);
   }
   /* Showing the contents of the list */
   void printlist(int list[],int n){
      int j;
   for(j=0;j<n;j++)
      printf("%d\t",list[j]);
}
void main(){
   int list[MAX], num;
   printf(" Enter the number of elements </p><p>");
   scanf("%d",&num);
   readlist(list,num);
   printf("</p><p></p><p>Elements in the list before sorting are:</p><p>");
   printlist(list,num);
   bub_sort(list,num);
   printf("</p><p></p><p>Elements in the list after sorting are:</p><p>");
   printlist(list,num);
}

##輸出

#執行上述程式時,會產生下列結果-

Enter the number of elements
10

Enter the elements:
11
23
45
1
3

6
35
69
10
22


Elements in the list before sorting are:
11 23 45 1 3 6 35 69 10 22

Elements in the list after sorting are:
1 3 6 10 11 22 23 35 45 69

以上是使用冒泡排序演算法對給定的數字列表進行升序排序的C程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除