You have to initialize the value for j as i+1, this sorting algorithm is called bubble sort, that works by repeatedly swapping the adjacent elements if they are in wrong order. The below method is always runs O(n^2) time even if the array is sorted.
public static void main (String[] args)
{
int[] array = {4,2,1,3,5,9,6,8,7};
for(int i = 0 ; i < array.length;i++)
{
for(int j = i+1 ; j< array.length;j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
Answer from apoori on Stack OverflowYou have to initialize the value for j as i+1, this sorting algorithm is called bubble sort, that works by repeatedly swapping the adjacent elements if they are in wrong order. The below method is always runs O(n^2) time even if the array is sorted.
public static void main (String[] args)
{
int[] array = {4,2,1,3,5,9,6,8,7};
for(int i = 0 ; i < array.length;i++)
{
for(int j = i+1 ; j< array.length;j++)
{
if(array[i] > array[j])
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
public int[] sort(int[] arr) {
int marker, i, temp;
marker =0;
i = 1;
while (marker < arr.length - 1) {
if (i == arr.length) {
marker++;
i = marker;
}
if (arr[marker] > arr[i]) {
temp = arr[marker];
arr[marker] = arr[i];
arr[i] = temp;
}
i++;
}
return arr;
}
So I'm still kind of a novice in java, and I would appreciate it if someone could explain what is a more preferred method in sorting the elements of an array in ascending order.
Shoul I use Loops? example:
-
//Sort the array in ascending order
-
for (int i = 0; i < arr.length; i++) {
-
for (int j = i+1; j < arr.length; j++) {
-
if(arr[i] > arr[j]) {
-
temp = arr[i];
-
arr[i] = arr[j];
-
arr[j] = temp;
Or is it more recomended to use Arrays.sort instead?
Or is it dependent on the usage?
Also what are the pros and cons of each.
Thank you to those who can enlighten me.
Edit: Thank you so much to everyone who shared their insights!