In Bubble Sort, smaller elements bubbles to top of list in ascending sorting hence it's called Bubble Sort.
How it works :
How it works :
- In Bubble Sort, You take first element and second element initially and compare both elements.
- If second element is smaller than first element then you swipe places. how? using temp :) as below
- You keep doing same meaning stepping through array and comparing element with pair of adjacent elements until no swapping required and you have sorted array
package com.anuj.algorithms; public class BubbleSort { protected void doBubbleSort(int data[], String sortingType) { int temp; for (int i = 0; i < data.length; i++) { //data[i] - individual array values for (int j = 0; j < data.length - 1; j++) { if (sortingType.equalsIgnoreCase("Ascending")) { if (data[j] > data[j + 1]) { temp = data[j]; data[j] = data[j + 1]; data[j+1] = temp; } } else if (sortingType.equalsIgnoreCase("Descending")) { if (data[j] < data[j + 1]) { temp = data[j]; data[j] = data[j + 1]; data[j+1] = temp; } } } } System.out.println("\nArray After " + sortingType + " Sorting : "); printArray(data); } protected void printArray(int[] data) { for (int i = 0; i < data.length; i++) { System.out.print(data[i]); if(i < data.length-1) { System.out.print(" "); } } } public static void main(String[] args) { BubbleSort bubbleSort = new BubbleSort(); int data[] = {1, 2, 33, 56, 8, 31}; System.out.println("Array Before Sorting : "); bubbleSort.printArray(data); bubbleSort.doBubbleSort(data, "Ascending"); bubbleSort.doBubbleSort(data, "Descending"); } }
Output :
Array Before Sorting : 1 2 33 56 8 31 Array After Ascending Sorting : 1 2 8 31 33 56 Array After Descending Sorting : 56 33 31 8 2 1
No comments:
Post a Comment