While learning the basics of Java, I encountered a problem with algorithms, so I wrote it for the sake of thinking.
Sort in ascending order (eg 2,5,3,4,1 → 1,2,3,4,5) By the way, descending order (5,4,3,2,1)
Images are compared and sorted one by one with a for statement from the left. (Comparative example: 2 and 5, 2 and 3, 2 and 4, 2 and 1 ...)
There are various ways to write it, but the following code example
1 int[] date = {2,5,3,4,1};
2 for (int i = 0; i < date.length - 1; i++) {
3 for (int j = i + 1; j < date.length ; j++) {
4 if (date[i] > date[j]) {
5 int a = date[i];
6 date[i] = date[j];
7 date[j] = a;
8 }
9 }
10}
11for (int i = 0; i < date.length; i++) {
12 System.out.print(date[i] + " ");
13}
In the for statement on the second line, specify the conditional expression to get the first element to be compared.
Initial value i= 0;Conditional expression(i < date.length - 1);Next step i++
Get the number of values that one element compares with `` `date.length --1```. It doesn't matter if the number of sorts increases.
The number of values to compare is, for example: 2,5,3,4,Of 1
2 and 5,2 and 3,2 and 4,2 and 1 4 times
Describe the conditional expression in the form of the initial value j = i + i
in order to get the second element to be compared in the for statement on the third line.
initial value(j = i +i);Conditional expression(j < date.length);Next step j++
The if statements on the 4th to 8th lines compare the values that meet the conditions and sort them.
if (date[i] > date[j]) {
int a = date[i];
date[i] = date[j];
date[j] = a;
}
Display of date after sorting
for (int i = 0; i < date.length; i++) {
System.out.print(date[i] + " ");
}
Console display
1 2 3 4 5
[Java] Sorting using arrays (Bubble sort)
Recommended Posts