Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Author: Andrew Closs
- * Version: 1.0
- * Date: December 18th, 2011.
- * Purpose: To sort a randomly generated 8 numbers via bubble sort.
- */
- package edu.hdsb.rbhs.ics3u.closs.u4;
- public class BubbleSort {
- public static int[] data = new int[8];
- public static int numberOfSwaps;
- public static int numberOfComparisons;
- 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 bubbleSort() {
- for (int pass = 0; pass < data.length - 1; pass++) {
- for (int i = 0; i < data.length - 1; i++) {
- numberOfComparisons = numberOfComparisons + 1;
- while (data[i] > data[i + 1]) {
- swap( data, i, i + 1 );
- 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();
- bubbleSort();
- 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