Skip to content

Instantly share code, notes, and snippets.

@Sisekelo
Created July 6, 2018 06:48
Show Gist options
  • Select an option

  • Save Sisekelo/2870a4135b4292e3bb051b6e88a6f80f to your computer and use it in GitHub Desktop.

Select an option

Save Sisekelo/2870a4135b4292e3bb051b6e88a6f80f to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class Solution {
private static int[] array; //empty int array
private static void bubbleSort() {
int n = array.length; // n is length of the
// number of swaps for all array iterations
int totalSwaps = 0;
//BUBBLE SORT = EXPECT LOOP WITHIN LOOP
for (int i = 0; i < n; i++) {
// number of swaps for current array iteration
int numSwaps = 0;
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) { //if number is bigger than the next one
int tmp = array[j]; //temp
array[j] = array[j + 1];//switch
array[j + 1] = tmp; //next = to temp
numSwaps++; //number of swaps increases
totalSwaps++; //total swap increase
}
}
if (numSwaps == 0) { //this means we have reached the end of the sort
System.out.printf("Array is sorted in %d swaps.\n", totalSwaps);
System.out.printf("First Element: %d\n", array[0]);
System.out.printf("Last Element: %d\n", array[n - 1]);
break;
}
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in); //takes in what is inputted
int n = in.nextInt(); //get the number of elements it expects
array = new int[n]; //creates array of length n
for (int i = 0; i < n; i++) {
array[i] = in.nextInt(); //puts all the numbers in array
}
in.close(); //close scanner
bubbleSort();//sort please.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment