Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
Node is saved as draft in My Content >> Draft
  • Bubble Sort in C

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 95
    Comment on it

    Bubble sort is a  sorting algorithm. This sorting is done by comparing the elements just after another in the iteration.

     

     

    Bubble sort comparison is based from the first and second element checking which one is greater.

     

    Bubble Sort

     

    Then each element is compared with iteration moves to the next element same process is been done.

     

    Bubble Sort

     

     

    Algorithm for Bubble sort

     

    1. begin BubbleSort(list)
    2.  
    3. for all elements of list
    4. if list[i] > list[i+1]
    5. swap(list[i], list[i+1])
    6. end if
    7. end for
    8. return list
    9. end BubbleSort

     

     

    1. #include <stdio.h>
    2. #include <stdbool.h>
    3.  
    4. #define MAX 10
    5.  
    6. int list[MAX] = {1,8,4,6,0,3,5,2,7,9};
    7.  
    8. void display(){
    9. int i;
    10. printf("[");
    11.     
    12. // navigate through all items
    13. for(i = 0; i < MAX; i++){
    14. printf("%d ",list[i]);
    15. }
    16.     
    17. printf("]\n");
    18. }
    19.  
    20. void bubbleSort() {
    21. int temp;
    22. int i,j;
    23.     
    24. bool swapped = false;
    25. // loop through all numbers
    26. for(i = 0; i < MAX-1; i++) {
    27. swapped = false;
    28.         
    29. // loop through numbers falling ahead
    30. for(j = 0; j < MAX-1-i; j++) {
    31. printf(" Items compared: [ %d, %d ] ", list[j],list[j+1]);
    32.  
    33. // check if next number is lesser than current no
    34. // swap the numbers.
    35. // (Bubble up the highest number)
    36.             
    37. if(list[j] > list[j+1]) {
    38. temp = list[j];
    39. list[j] = list[j+1];
    40. list[j+1] = temp;
    41.  
    42. swapped = true;
    43. printf(" => swapped [%d, %d]\n",list[j],list[j+1]);
    44. }else {
    45. printf(" => not swapped\n");
    46. }
    47.             
    48. }
    49.  
    50. // if no number was swapped that means
    51. // array is sorted now, break the loop.
    52. if(!swapped) {
    53. break;
    54. }
    55. printf("Iteration %d#: ",(i+1));
    56. display();
    57. }
    58.     
    59. }
    60.  
    61. main(){
    62. printf("Input Array: ");
    63. display();
    64. printf("\n");
    65.     
    66. bubbleSort();
    67. printf("\nOutput Array: ");
    68. display();
    69. }

     

     

    .net

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: