On the bubble algorithm

The first contact sorting algorithm bubble sort, first of all to look at what is called the bubble sort, assuming a large number of relatively heavy, the smaller the number of light, so when comparing the two would lead to a large number of bottom while a small number will float;

Suppose an array arr [10] = {2, 1, 3, 5, 6, 4, 7, 9, 8, 10}, if such a bubbling unordered array by sorting algorithm, it will introduce a term called times , if we are in ascending order, then the first trip in dozens of pairwise comparison would be more nine times, second trip in pairwise comparison would be more eight times, being so, will this ten It will be 9 times the number of sorting, comparison 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 so many times, that knows so many times, but not used, we just write it out; no nonsense to say directly on the code;

#include<stdio.h>
void bubble_sort(int arr[], int sz)
{
 int i = 0;
 int j = 0;
 for (i = 0; i < sz-1; i++)
 {
  for (j = 0; j <sz-1-i ; j++)
  {
   if (arr[j]>arr[j + 1])
   {
    int tmp = arr[j];
    arr[j] = arr[j + 1];
    arr[j + 1] = tmp;
   }
  }
 }
}
void print_arr(int arr[], int sz)
{
 int i = 0;
 for (i = 0; i < sz; i++)
 {
  printf("%d ", arr[i]);
 }
 
}
int main()
{
 int arr[10] = { 2, 1, 3, 5, 6, 4, 7, 9, 8, 10 };
 int sz = sizeof(arr) / sizeof(arr[0]);
 print_arr(arr, sz);
 bubble_sort(arr, sz);
 printf("\n");
 print_arr(arr, sz);
 return 0;
}

Such code is still able to optimize part; we can think about this way of thinking we are completely in accordance with the number of this group of disorderly conduct, but if this group if the number of ordered it; a good look at this Code; just void bubble_sort been modified other code has not changed;

void bubble_sort(int arr[], int sz)
{
 int i = 0;
 int j = 0;
 for (i = 0; i < sz-1; i++)
 {
  int flag = 1//假设有序
  for (j = 0; j <sz-1-i ; j++)
  {
   if (arr[j]>arr[j + 1])
   {
    int tmp = arr[j];
    arr[j] = arr[j + 1];
    arr[j + 1] = tmp;
    flag = 0;//无序
   }
  }
  if(flag == 1)
  {
  return;
  }
 }
}

This improves the efficiency of the code;

Published 20 original articles · won praise 9 · views 913

Guess you like

Origin blog.csdn.net/weixin_44915811/article/details/90110350