Last active
December 12, 2021 17:31
-
-
Save sunmeat/a7ef514899a20be8080c to your computer and use it in GitHub Desktop.
insertion sort code example for android 8
This file contains hidden or 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 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