Saturday, February 12, 2011

Java Bubble Sort Descending Order


  1. /*
  2. Java Bubble Sort Descending Order Example
  3. This Java bubble sort example shows how to sort an array of int in descending
  4. order using bubble sort algorithm.
  5. */
  6.  
  7. public class BubbleSortDescendingOrder {
  8.  
  9. public static void main(String[] args) {
  10.  
  11. //create an int array we want to sort using bubble sort algorithm
  12. int intArray[] = new int[]{5,90,35,45,150,3};
  13.  
  14. //print array before sorting using bubble sort algorithm
  15. System.out.println("Array Before Bubble Sort");
  16. for(int i=0; i < intArray.length; i++){
  17. System.out.print(intArray[i] + " ");
  18. }
  19.  
  20. //sort an array in descending order using bubble sort algorithm
  21. bubbleSort(intArray);
  22.  
  23. System.out.println("");
  24.  
  25. //print array after sorting using bubble sort algorithm
  26. System.out.println("Array After Bubble Sort");
  27. for(int i=0; i < intArray.length; i++){
  28. System.out.print(intArray[i] + " ");
  29. }
  30.  
  31. }
  32.  
  33. private static void bubbleSort(int[] intArray) {
  34.  
  35. /*
  36. * In bubble sort, we basically traverse the array from first
  37. * to array_length - 1 position and compare the element with the next one.
  38. * Element is swapped with the next element if the next element is smaller.
  39. *
  40. * Bubble sort steps are as follows.
  41. *
  42. * 1. Compare array[0] & array[1]
  43. * 2. If array[0] < array [1] swap it.
  44. * 3. Compare array[1] & array[2]
  45. * 4. If array[1] < array[2] swap it.
  46. * ...
  47. * 5. Compare array[n-1] & array[n]
  48. * 6. if [n-1] < array[n] then swap it.
  49. *
  50. * After this step we will have smallest element at the last index.
  51. *
  52. * Repeat the same steps for array[1] to array[n-1]
  53. *
  54. */
  55.  
  56. int n = intArray.length;
  57. int temp = 0;
  58.  
  59. for(int i=0; i < n; i++){
  60. for(int j=1; j < (n-i); j++){
  61.  
  62. if(intArray[j-1] < intArray[j]){
  63. //swap the elements!
  64. temp = intArray[j-1];
  65. intArray[j-1] = intArray[j];
  66. intArray[j] = temp;
  67. }
  68.  
  69. }
  70. }
  71.  
  72. }
  73. }
  74.  
  75. /*
  76. Output of the Bubble Sort Descending Order Example would be
  77.  
  78. Array Before Bubble Sort
  79. 5 90 35 45 150 3
  80. Array After Bubble Sort
  81. 150 90 45 35 5 3
  82.  
  83. */

No comments:

Post a Comment