Let's look at the bubble sort algorithm today.
The bubble sort algorithm sorts a list of given items by comparing each element with the next element.
So let's say, we have the following list of integers {222, 3, 343, 545, 9, 99, 68, 11}, and we had to sort this list.
Bubble sort is one of the ways to do this.
Bubble sort algorithm says that, we have to take the elements one by one and compare it with the next element. If the next element is greater than current element don't do anything. However, if the next element is less than current element swap them.
We should keep doing this, until all the elements are sorted. Please find below an implementation in Java, of the bubble sort algorithm.
package org.praveen.java.learning;
public class MyBubbleSort {
public static void main(String[] args) {
int[] inputArray = { 1, 44, 3, 788, 54, 5, 66, 4, 2, 3, 333, 43, 34, 45,
666, 7, 77, 8, 8877, 6, 544, 34, 33, 34, 5, 9 };
for (int iVal = 0; iVal < inputArray.length-1; iVal++) {
for (int jVal = iVal; jVal > 0; jVal--) {
if (inputArray[jVal] > inputArray[jVal + 1]) {
int temp = inputArray[jVal];
inputArray[jVal] = inputArray[jVal + 1];
inputArray[jVal + 1] = temp;
}
}
}
for(int uuu: inputArray){
System.out.println(uuu);
}
}
}
No comments:
Post a Comment