C language bubble sorting

  • 2020-05-09 18:51:52
  • OfStack

I remember when I was studying c in university, it was very difficult at the beginning.

One of the entry level algorithms is called bubble sort, or bubble sort, and it was very interested in its name at the time, because it was very interesting.

  1. Print line and column 1 like this 1 simple code, output 4 lines 4 columns *:


for(int i = 1,i < 5,i++){
   for(int j = 1,j < 5,j++){
   printf("*");
  }
  printf("n\");
}

  2. Print "top 3 ":


for(int i = 1,i < 5,i++){
   for(int j = 1,j < i,j++){
   printf("*");
  }
  printf("n\");
}

3. Print "bottom 3 ":


for(int i = 1,i < 5,i++){
   for(int j = i,j < 5,j++){
   printf("*");
  }
  printf("n\");
}

4. The reader don't worry, and the place of key came. Bubble sort is a principle of "three Angle under the" print, because in a sorting always starts from the first element in the array and the back of the elements to one wheel, determine the value of 1, the most value on "sink" in the last one, compare each round will be less number 1, so bubble sort principle is used to print "3 Angle under the principle of" :


for (int i = 0; i < 4; i++) {
    for (int j = i; j < 4; j++) {
      if (nums[j] < nums[j+1]) {
        int temp = nums[j];
        nums[j] = nums[j+1];
        nums[j+1] = temp;
      }
    }
    
  }

Careful friends should find that after sorting an array like this, the result will not be the expected result, but I clearly used "print next 3 jiao"! Remember at that time the teacher gave us such a homework, let you go back to think, prompt with the "next 3" principle to print, at that time feel good pit dad! (so this bubble sort is still pretty impressive.)

5. Yes, this is one small detail, I was thinking about the good 1 matrix, finally found the problem, because each comparison under 1 round begin to count from the front of and behind the number of the comparison, if you change the value of the initialization can be compared with the number 2 once the number 1 will not participate in after 1 round comparison. So we should put this in one kind of form


for (int i = 0; i < 4; i++) {
    for (int j = 0; j < 4-i; j++) {
      if (nums[j] < nums[j+1]) {
        int temp = nums[j];
        nums[j] = nums[j+1];
        nums[j+1] = temp;
      }
    }
    
  }

6. Haha, the principle is good, after changing one form, the output is no problem.

7. Add 1 point, 1 will have replaced 4 for a variable, such as length, or using the macro definition method, the individual feels better. A macro definition when using length to length - 1, so have a good, is to prevent cross-border problems, and sort than the rest of the size of the time the last one was also need not to compare. So length - 1 is no problem.


Related articles: