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 boolean doSwap;
- 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 ; i++) {
- for ( int j = 0; j < data.length ; j++) {
- if (data[i] > data[j]){
- doSwap = true;
- }
- swap(data, i, j);
- numberOfComparisons = numberOfComparisons + 1;
- }
- /* numberOfComparisons = numberOfComparisons + 1;
- while (data[i] > data[j]) {
- tOrF = 1;
- }
- }
- if (tOrF == 1) {
- swap(data, i, j);
- numberOfSwaps = numberOfSwaps + 1;
- System.err.println("Boners");
- */
- }
- }
- }
- public static void swap(int[] a, int i, int j) {
- if (doSwap == true){
- int temp;
- temp = data[i];
- data[i] = data[j];
- data[j] = temp;
- numberOfSwaps = numberOfSwaps + 1;
- }
- }
- 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