Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active December 12, 2021 17:31
Show Gist options
  • Save sunmeat/a7ef514899a20be8080c to your computer and use it in GitHub Desktop.
Save sunmeat/a7ef514899a20be8080c to your computer and use it in GitHub Desktop.
insertion sort code example for android 8
package yourPackage;
public class YourClassName {
public static void main(String[] args) {
int size = 10;
int ar[] = new int[size];
// before sort
for (int i = 0; i < size; i++) {
ar[i] = (int) (Math.random() * 100);
System.out.print(ar[i] + " ");
}
System.out.print("\n\n");
// start sort
for (int pr = 0; pr < size; pr++) {
int value = ar[pr];
int index;
// search place for element
for (index = pr - 1; index >= 0 && ar[index] > value; index--) {
ar[index + 1] = ar[index]; // move element to right
}
// find place - insert
ar[index + 1] = value;
}
// after sort
for (int i = 0; i < size; i++) {
System.out.print(ar[i] + " ");
}
System.out.println("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment