175k views
1 vote
Write a function in Java that takes in the int[] array, sorts it using bubble sort, then returns back the sorted array.

User Sungjun
by
7.5k points

1 Answer

4 votes

Answer

//Class to test the bubble sort

public class BubbleSortTest{

//Method to sort the array using bubbleSort

//Takes the array to be sorted as argument

public static int[] bubbleSort(int[] arr) {

//Create an integer to hold the length of the array

int n = arr.length;

//Create a temporary variable to hold the values of the

//array

//for swapping purposes. Initialize it to zero

int temp = 0;

//Cycle through the array element by element

for(int i = 0; i < n; i++){

//For each element

for(int j = 1; j < (n-i); j++){

//if the element is greater than the element after it

if(arr[j-1] > arr[j]){

//swap the elements

temp = arr[j-1];

arr[j-1] = arr[j];

arr[j] = temp;

} //End of if

} //End of inner for

} //End of outer for

//return the sorted array

return arr;

}

//main method

public static void main(String [] args){

//create a sample array

int [] myArray = {56, 23, 7, 4, 6};

//Call the bubbleSort() method to sort the array

int [] sortedArray = bubbleSort(myArray);

//Print out the sorted array

for(int i = 0; i < sortedArray.length; i++){

System.out.print(sortedArray[i] + " ");

}

} //End of main method

} //End of class BubbleSortTest

Sample Output

4 6 7 23 56

Step-by-step explanation:

The code above has been written in Java and it contains comments explaining necessary parts of the code. Please go through the comments. A sample output has also been provided.

For clarity, the following shows the actual function alone without using or including it in a class.

=========================================================

//Method to sort the array using bubbleSort

//Takes the array to be sorted as argument

public static int[] bubbleSort(int[] arr) {

//Create an integer to hold the length of the array

int n = arr.length;

//Create a temporary variable to hold the values of the array

//for swapping purposes. Initialize it to zero

int temp = 0;

//Cycle through the array element by element

for(int i = 0; i < n; i++){

//For each element

for(int j = 1; j < (n-i); j++){

//if the element is greater than the element after it

if(arr[j-1] > arr[j]){

//swap the elements

temp = arr[j-1];

arr[j-1] = arr[j];

arr[j] = temp;

}

}

}

//return the sorted array

return arr;

}

=========================================================

User Connersz
by
7.0k points