Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SelectionSort {
- public static int[] data = new int[8];
- public static int numberOfSwaps;
- public static int numberOfComparisons;
- public static int tOrF;
- public static int j;
- public static void randomizingArray() {
- for (int i = 0; i < data.length; i++) {
- data[i] = (int) (1000 * Math.random()) + 1;
- System.out.print(data[i] + ", ");
- }
- }
- public static void selectionSort() {
- for (int pass = 0; pass < data.length - 1; pass++) {
- for (int i = 0; i < data.length - 1; i++) {
- for ( j = 0; j < data.length - 1; j++) {
- numberOfComparisons = numberOfComparisons + 1;
- while (data[i] > data[j]) {
- tOrF = 1;
- }
- }
- if (tOrF == 1) {
- swap(data, i, j);
- numberOfSwaps = numberOfSwaps + 1;
- }
- }
- }
- }
- public static void swap(int[] a, int i, int j) {
- int temp;
- temp = data[i];
- data[i] = data[j];
- data[j] = temp;
- }
- public static void main(String[] args) {
- System.out.println("Unsorted data: ");
- randomizingArray();
- selectionSort();
- System.out.println("\n\nSorted data: ");
- for (int i = 0; i < data.length; i++) {
- System.out.print(data[i] + ", ");
- }
- System.out.println("\n");
- System.out.println("Number of Comparisons: " + numberOfComparisons + "\n" + "Number of Swaps: " + numberOfSwaps);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement