Created
September 8, 2017 00:05
-
-
Save blzjns/5b318b295213993ce5a36285499ed768 to your computer and use it in GitHub Desktop.
Bubble Sort Sample with Comments
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import java.util.Arrays; | |
public class BubbleSortExample { | |
public static void main(String[] args) { | |
int[] list = {34, 203, 3, 746, 200, 984, 198, 764, 9}; // list of numbers, aka: array | |
bubbleSort(list); | |
System.out.println(Arrays.toString(list)); | |
} | |
public static void bubbleSort(int[] numArray) { | |
int n = numArray.length; // list/array size | |
int temp = 0; // temporary variable | |
for (int i = 0; i < n; i++) { //for each item in the list/array | |
for (int j = 1; j < (n - i); j++) { // for every other item (except the current one) | |
int currentItem = numArray[j - 1]; | |
int nextInnerItem = numArray[j]; | |
if (currentItem > nextInnerItem) { // compare if current item is greater than inner item | |
// if "yes"/true | |
temp = currentItem; | |
numArray[j - 1] = numArray[j]; // move next item to current item's position | |
numArray[j] = temp; // move current item to next item's position | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment