January 21, 2020

How to Create a Bubble sort in Java

Bubble sort is a simple sorting algorithm that repeatedly steps through the list should be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. Do you know why its called as Bubble sort because The smaller value bubbles up to the top of the list, while the larger value sinks to the bottom.
[Download Source code]

BubbleSort.java
1 package com.techieprogrammer; 2 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.Iterator; 6 import java.util.List; 7 8 class BubbleSortCompute { 9 static List <Integer> intList = new ArrayList <Integer>(); 10 11 public static void add(List <Integer> temp) { 12 intList.clear(); 13 Iterator<Integer> ptr = temp.iterator(); 14 while(ptr.hasNext()) { 15 intList.add(ptr.next()); 16 } 17 } 18 19 public static void sort() { 20 System.out.println("Before Bubble Sort:"); 21 Iterator<Integer> ptr = intList.iterator(); 22 while(ptr.hasNext()) { 23 System.out.print(ptr.next()+" "); 24 } 25 System.out.println("\n\nAfter Bubble Sort:"); 26 compute(); 27 ptr = intList.iterator(); 28 while(ptr.hasNext()) { 29 System.out.print(ptr.next()+" "); 30 } 31 } 32 33 private static void compute() { 34 int temp; 35 int intListSize = intList.size(); 36 for(int outerCounter = 0;outerCounter < intListSize; outerCounter++) { 37 for(int interCounter = 0;interCounter < intListSize - outerCounter - 1; interCounter++) { 38 if(intList.get(interCounter) >= intList.get(interCounter+1)) { 39 temp = intList.get(interCounter+1); 40 intList.set(interCounter+1, intList.get(interCounter)); 41 intList.set(interCounter, temp); 42 } 43 } 44 } 45 } 46 } 47 48 public class BubbleSort { 49 //Entry Point 50 public static void main(String[] args) { 51 List <Integer> intList = new ArrayList <Integer>(Arrays.asList(50,2,5,78,90,20,4,6,98,1)); 52 BubbleSortCompute.add(intList); 53 BubbleSortCompute.sort(); 54 } 55 }
If you love this article, please share your comments or follow our social media page.

No comments:

Post a Comment


Power by Blogger