Ikkinchi oʻtish
(1 4 2 5 8) → (1 4 2 5 8)
(1 4 2 5 8) → (1 2 4 5 8), 4 > 2 dan beri almashtirish
(1 2 4 5 8) → (1 2 4 5 8)
(1 2 4 5 8) → (1 2 4 5 8)
Endi massiv allaqachon tartiblangan, lekin algoritm uning tugallanganligini bilmaydi. Algoritm tartiblanganligini bilish uchun uni almashtirishsiz yana bitta toʻliq oʻtish kerak.
Uchinchi oʻtish
(1 2 4 5 8) → (1 2 4 5 8)
(1 2 4 5 8) → (1 2 4 5 8)
(1 2 4 5 8) → (1 2 4 5 8)
(1 2 4 5 8) → (1 2 4 5 8)
Algoritmi va dasturi[tahrir | manbasini tahrirlash]
public class BubbleSort {
public static void main(String[] args) {
int[] massiv = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
int n = massiv.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (massiv[i] > massiv[k]) {
int temp;
temp = massiv[i];
massiv[i] = massiv[k];
massiv[k] = temp;
}
}
for (int i = 0; i < massiv.length; i++) {
System.out.print(massiv[i] + ", ");
}
System.out.println(„\n“);
}
}
}
Chiqariluvchi natijamiz esa:
2, 4, 6, 9, 12, 23, 0, 1, 34, // 1-qadam.
2, 4, 6, 9, 12, 0, 1, 23, 34, //2-qadam.
2, 4, 6, 9, 0, 1, 12, 23, 34,//3-qadam.
2, 4, 6, 0, 1, 9, 12, 23, 34,//4-qadam.
2, 4, 0, 1, 6, 9, 12, 23, 34,//5-qadam.
2, 0, 1, 4, 6, 9, 12, 23, 34,//6-qadam.
0, 1, 2, 4, 6, 9, 12, 23, 34, //7-qadam.
0, 1, 2, 4, 6, 9, 12, 23, 34, //8-qadam.
0, 1, 2, 4, 6, 9, 12, 23, 34,//9-qadam.
0, 1, 2, 4, 6, 9, 12, 23, 34, // saralangan holdagi massiv.
Algoritmlarni loyihalsh va tahlil qilish bosqichlari.
Do'stlaringiz bilan baham: |