Bubble Sort Implementation in C Language

“To become a master, it takes time and effort, unless you are a natural talent in martial arts, but such people are… rare.”
——The Landlady
This principle applies to learning C language as well. There are indeed few people with exceptional talent in programming; most of us need to accumulate knowledge gradually to progress from a novice to an expert in C language.
So how do we learn?Of course, practice one C language problem every day!

Bubble Sort Implementation in C Language

Author

Yan Xiaolin

Working during the day, dreaming at night. I have stories, do you have wine?

Example 23: Implement a sorting algorithm in C language to sort ten numbers in ascending order using bubble sort.
Problem-solving idea: There are two types of sorting: one is “ascending”, from small to large; the other is “descending”, from large to small.
Source code demonstration:
#include<stdio.h>//Header file 
int main()//Main function 
{
  int i,j,t;//Define integer variables 
  int array[10];//Define array size 
  printf("Please enter ten numbers:");//Prompt statement 
  for(i=0;i<10;i++)//Manually input 10 numbers into the array 
  {
    scanf("%d,",&array[i]);//Note the & symbol 
  } 
  for(j=0;j<9;j++)//Outer loop limit 
  {
    for(i=0;i<9-j;i++)//Inner loop 
    if(array[i]>array[i+1])//If the previous number is greater than the next number 
    {
      t=array[i]; //Assign the smaller number to the front, and the larger number to the back 
      array[i]=array[i+1];
      array[i+1]=t;
    }
  } 
  printf("Sorted in ascending order:");//Prompt statement 
  for(i=0;i<10;i++)//Loop to output 10 numbers 
  {
    printf("%d ",array[i]);
  } 
  printf("\n");//New line 
  return 0;//Function return value is 0 
}
The compilation and running results are as follows:
Please enter ten numbers:9 8 4 1 6 2 7 4 10 9
Sorted in ascending order:1 2 4 4 6 7 8 9 9 10

--------------------------------
Process exited after 20.46 seconds with return value 0
Press any key to continue...
This is the well-known “bubble sort”, also known as “sinking sort”. Readers can gain insights from this example for learning quick sort, heap sort, etc.
Leave a question: How would you sort in descending order?
If you found this helpful, please give Xiaolin a thumbs up and share it with those around you. This motivates Xiaolin to keep updating. Thank you all very much!

Follow the public account below, reply 1 to be added to a programming community of 15,000 people for free, and receive 100 C language source code examples, including Snake Game, Tetris, Heart-Shaped Confession, Christmas Tree source code~

Click to follow and quickly get started with C language.

Leave a Comment