191k 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. Examples:

1 Answer

6 votes

Answer:

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

int n = arr.length;

int temp = 0;

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

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

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

temp = arr[j-1];

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

arr[j] = temp;

}

}

}

return arr;

}

Step-by-step explanation:

Above function is written in java language in which it takes integer array then sorts it using bubble sort and return back the array. The function has return type int[] which is necessary for returning array of type integer. The variable n contains the size of array which is calculated through array's length method which is built in. Above function sorts array in descending order if you want to sort it in ascending order just change the condition of in if branch from "if(arr[j-1] > arr[j])" to "if(arr[j-1] < arr[j])" means replace > sign with < sign .

User Scott Buchanan
by
5.8k points