this is something I got online, and also used my own code, but I am having some trouble calling the method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | package bubblesorting; /** * * @author Jacqueline Reilly */ public class BubbleSorting { /** * @param args the command line arguments */ public static void main(String[] args) { // Source code starts here //Declaring one dimensional array int [] list = new int [ 6 ]; //Loop that generates random numbers in the range 1 - 100 for ( int i = 0 ; i < list.length; i++) { list[i] = ( int ) (Math.random() * 100 + 1 ); } //Printing a display statement System.out.println( "Order before sorting: " ); //Displaying the numbers before sorting //The loop will run 6 times, since that is the length of the array for ( int i = 0 ; i < list.length; i++) { System.out.print(list[i] + " " ); } System.out.println( " " ); //Calling the bubble sort method. Calling array to sort values in array //It is going to sort the values in the array called list bubbleSort(list); //Printing display statements System.out.println( " " ); System.out.println( "Order after sorting: " ); //Displaying the numbers after the sorting //The loop will run 6 times, since that is the length of the array for ( int i = 0 ; i < list.length; i++) { System.out.print(list[i] + " " ); } } //Method for the bubble sort algorithm public int [] bubbleSort( int [] list) { // Variable declarations int i, x, swap; //i is loop control variable for outer loop //x is loop control variable for inner loop //swap is for the swaps for (i = 0 ; i < list.length - 1 ; i++) { //the outer loop will run from 0 to the lenght of list -1 for (x = 0 ; x < list.length - 1 - 1 ; x++) { //inner loop will from 0 to length of list - 1 - i //i is the number of items that are already sorted (the number of complete iterations) if (list[x] > list[x + 1 ]) { //Comparing the element on left to the element to the right of it. //if it is greater than item on the right, the swap happens. //Swapping elements swap = list[x]; //the swap equals that element it is swapping list[x] = list[x + 1 ]; //that element is now going to equal that element +1 so it will look at the element that is right next to it list[x + 1 ] = swap; //this is swapping the element to the right } } } return list; //Returning sorted list of numbers } } |