C language exercises bubble sort [10]

Bubble sort (the Sort Bubble) , is simpler sorting algorithm a field of computer science. It repeatedly visited elements of the column to sort, in order to compare two adjacent elements, if the order (such as descending, the first letter from Z to A) put the wrong they exchanged over. Working visit element is repeated until there is no need to swap adjacent elements, that is to say the element column has been sorted completed. The name comes from the fact algorithm smaller elements will gradually exchange via a "float" to the top of the column number (ascending or descending order), as if the carbon dioxide bubbles in a carbonated beverage eventually float to the top of the same, hence the name "bubble sort. "

#include<stdio.h>
void sort(int arr[],int len)
{
 int j = 0;
 for (j = 0; j < len - 1; j++)
 {
  int flag = 1;
  int i = 0;
  for (i = 0; i < len - 1 - j; i++)
  {
   if (arr[i] > arr[i + 1])
   {
    int temp = arr[i];
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
    flag = 0;
   }
  }
  if (flag == 1)
  {
   break;
  }
 }
}
int main()
{
 int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
 int len = sizeof(arr)/sizeof(arr[0]);
 sort(arr,len);
 for (int i = 0; i<len; i++)
 {
  printf("%d ", arr[i]);
 }
 return 0;
}

The optimizer is used with a flag, if the first pass sequencing requirements satisfied, can bounce.

Guess you like

Origin blog.51cto.com/14737345/2480427