Pages

sort array in java

How to sort array in java using for loop ?

>> We can sort given array in ascending / descending order using for loop.

import java.util.Arrays;
public class sortArray {
public static void main(String[] args) {
int a[] = { 3, 2, 1, 5, 6, 4, 9, 7, 8 };

int temp = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Array in ascending order=");
for (int num : a) {
System.out.print(num + " ");
}

System.out.println(
"\n<<----------------------------------->>");
int temp1 = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] < a[j]) {
temp1 = a[i];
a[i] = a[j];
a[j] = temp1;
}
}
}
System.out.print("Array in descending order=");
for (int num : a) {
System.out.print(num + " ");
}

System.out.println(
"\n<<----------------------------------->>");
System.out.print("Array in ascending order using Arrays.sort()=");
int b[] = { 3, 2, 1, 5, 6, 4, 9, 7, 8, -4, 10, -6 };
Arrays.sort(b);
for (int n : b) {
System.out.print(n + " ");
}
}

}
Output:
sort array in java

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.