for i from 0 to n - 2 do for j from n-1 down to i + 1 do if a[j-1] > a[j] { temp = a[j-1]; a[j-1] = a[j]; a[j] = temp }
Outer loop: n = 8, i = 0 to 6, repeat seven times Inner loop: for j = n(8) - 1 down to i(0) + 1 do if (a[j-1] > a[j]) swap([j-1],a[j]) First pass: { 7, 3, 66, 3, -5, 22, -77, 2}; i = 0; j = 7 Second pass: { 7, 3, 66, 3, -5, -77, 22, 2}; i = 0; j = 6 Third pass: { 7, 3, 66, 3, -77, -5, 22, 2}; i = 0; j = 5 Fourth pass: { 7, 3, 66, -77, 3, -5, 22, 2}; i = 0; j = 4 Fifth pass: { 7, 3, -77, 66, 3, -5, 22, 2}; i = 0; j = 3 Sixth pass: { 7, -77, 3, 66, 3, -5, 22, 2}; i = 0; j = 2 Seventh pass: { -77, 7, 3, 66, 3, -5, 22, 2}; i = 0; j = 1 Second pass: { -77, -5, 7, 3, 66, 3, 2, 22}; i = 1; j = 7 down to 2 Third pass: { -77, -5, 2, 7, 3, 66, 3, 22}; i = 2; j = 7 down to 3 Fourth pass: { -77, -5, 2, 3, 7, 3, 66, 22}; i = 3; j = 7 down to 4 Fifth pass: { -77, -5, 2, 3, 3, 7, 22, 66}; i = 4; j = 7 down to 5 Sixth pass: { -77, -5, 2, 3, 3, 7, 22, 66}; i = 5; j = 7 down to 6 Seventh pass: { -77, -5, 2, 3, 3, 7, 22, 66}; i = 6; j = 7 down to 7
class Sorting { public static void main(String[] args) { int[] a = new int[args.length]; for (int i = 0; i < args.length; i++) a[i] = Integer.parseInt(args[i]); for (int i = 0; i < a.length - 1; i++) for (int j = a.length - 1; i < j; j--) { if (a[j-1] > a[j]) { int temp = a[j-1]; a[j-1] = a[j]; a[j] = temp; } } for (int i = 0; i < a.length; i++) System.out.println(a[i]); } }
import java.util.*; class Sorting1 { public static void main(String[] args) { int[] a = new int[args.length]; for (int i = 0; i < args.length; i++) a[i] = Integer.parseInt(args[i]); Arrays.sort(a); for (int i = 0; i < a.length; i++) System.out.println(a[i]); } }
public static void swap(int[] arr, int i1, int i2) throws ArrayIndexOutOfBoundsException { int temp = arr[i1]; arr[i1] = arr[i2]; arr[i2] = temp; } public static void bubbleSort(int[] arr) { final int PASSES_NEEDED = arr.length - 1; int temp; // used for the swap for (int pass = 0; pass < PASSES_NEEDED; ++pass) { for (int i = 0; i + 1 < arr.length - pass; ++i) { if (arr[i] > arr[i + 1]) { swap(arr, i, i + 1); } } } }
Previou page | Next page |