Created
June 6, 2022 16:01
-
-
Save eutkin/f0f0866c1c0ef7db9cf0a14e3d69d2ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.yseagull; | |
import java.util.Arrays; | |
import java.util.Random; | |
public class App { | |
public static void main(String[] args) { | |
// Инициализируем массив из 10 элементов (ячеек). Каждая ячейка хранит одно число. | |
int[] array = new int[10]; | |
/* | |
index 0 1 2 3 4 5 6 7 8 9 | |
array | | | | | | | | | | - 4 байт (Integer.BYTES) | |
*/ | |
// заполняем каждую ячейку случайным числом. Для этого делаем цикл от 0 до длины массива, | |
// используя переменную index. Переменная index будет соответствовать индексу элемента в массиве, то есть | |
// его номер в массиве. Заполняем случайным числом от 0 до 50. Число 50 выбрано произвольно. | |
for (int index = 0; index < array.length; index++) { | |
array[index] = new Random().nextInt(50); | |
} | |
// Выводим полученный массив на экран | |
System.out.println(Arrays.toString(array)); | |
int[] sortedArray = sort(array); | |
System.out.println(Arrays.toString(sortedArray)); | |
} | |
public static int[] sort(int[] input) { | |
// [8, 49, 2, 11, 39, 18, 20, 8, 1, 36] | |
// i = 0 | |
// j = 1: [8, 49, 2, 11, 39, 18, 20, 8, 1, 36] | |
// j = 2: [8, 2, 49, 11, 39, 18, 20, 8, 1, 36] | |
// j = 3: [8, 2, 11, 49, 39, 18, 20, 8, 1, 36] | |
// j = 4: [8, 2, 11, 39, 49, 18, 20, 8, 1, 36] | |
// j = 5: [8, 2, 11, 39, 18, 49, 20, 8, 1, 36] | |
// j = 6: [8, 2, 11, 39, 18, 20, 49, 8, 1, 36] | |
// j = 7: [8, 2, 11, 39, 18, 20, 8, 49, 1, 36] | |
// j = 8: [8, 2, 11, 39, 18, 20, 8, 1, 49, 36] | |
// j = 9: [8, 2, 11, 39, 18, 20, 8, 1, 36, 49] | |
// i = 1 | |
// j = 1: [2, 8, 11, 39, 18, 20, 8, 1, 36, 49] | |
// j = 2: [2, 8, 11, 39, 18, 20, 8, 1, 36, 49] | |
// j = 3: [8, 2, 11, 49, 39, 18, 20, 8, 1, 36] | |
// j = 4: [8, 2, 11, 39, 49, 18, 20, 8, 1, 36] | |
for (int iteration = 0; iteration < input.length; iteration++) { | |
for (int index = 1; index < input.length; index++) { | |
if (input[index - 1] > input[index]) { | |
int buffer = input[index - 1]; // 49 при index = 2 | |
input[index - 1] = input[index]; // 49 -> 2 при index = 2 | |
input[index] = buffer; // 2 -> 49 при index = 2 | |
} | |
} | |
} | |
return input; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment