Sorting in ascending order in Java (bubble sort: simple exchange algorithm)

Sorting in ascending order in Java (bubble sort: simple exchange algorithm)

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

reference


[Java] Sorting using arrays (Bubble sort)

Recommended Posts

Sorting in ascending order in Java (bubble sort: simple exchange algorithm)
Sort Map values in ascending key order in Java TreeMap
Implemented basic search / sort algorithm in Java
java bubble sort
Implement the algorithm in Ruby: Day 2 -Bubble sort-
[java] sort in list
Simple htmlspecialchars in Java
How to sort in ascending / descending order with SQLite
Get location information in Rails and sort in ascending order
[Neta] Sleep Sort in Java
2 Implement simple parsing in Java
Bubble sort using ArrayList (JAVA)
Sort List in descending order in Java and generate a new List non-destructively
I tried to sort the data in descending order, ascending order / Rails
Very simple input reception in Java
3 Implement a simple interpreter in Java
A simple sample callback in Java
1 Implement simple lexical analysis in Java
Member description order in Java coding convention
Make bubble sort and selection sort in Ruby