Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void swap(int[] array, int posA, int posB) {
- /*
- Description: Swaps two values in an int array
- Parameters: int array of values and positions of elements to be swapped
- Returns: void
- */
- // Task: Complete method code
- int tmp;
- tmp = array[posA];
- array[posA] = array[posB];
- array[posB] = tmp;
- }
- public static void bubbleSort(int[] array) {
- /*
- Description: Sorts a int array using bubblesort algoritm
- Parameters: int array of values to be sorted
- Returns: void
- */
- // Task: Complete method code and count number of comparisons and swaps
- int comp = 0, swaps = 0, posA, posB;
- for (int out = array.length - 1; out > 0; out--) {
- comp++;
- for (int in = 0; in < out; in++) {
- if (array[in] > array[in + 1]) {
- posA = in;
- posB = in + 1;
- swap(array, posA, posB);
- swaps++;
- }
- }
- }
- System.out.println("The array is now sorted, the amount of comparisons is " + comp + ", and the number of swaps is " + swaps);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement