Question

Aim To improve the algorithm provided in Snippet 2.3 by reducing the number of passes. public...

Aim

To improve the algorithm provided in Snippet 2.3 by reducing the number of passes.

public void sortImprovement1(int[] numbers) {
    for (int i = 1; i < numbers.length; i++) {
        for (int j = 0; j < numbers.length - i; j++) {
            if (numbers[j] > numbers[j + 1]) {
                swap(numbers, j, j + 1);
            }
        }
    }
}

Snippet 2.3: Bubble sort improvement 1

Change the bubble sort method so that it stops sorting if the array is untouched after an inner loop pass.

Consider changing the outer for loop into a while loop.

Steps for Completion

The solution can be developed easily if the outer for loop is changed into a while loop and a flag is kept to indicate if any elements have been swapped while going through the array. This is shown in the following code block:

public  void  sortImprovement2(int[]  numbers)  {
    int  i  =  0;
    boolean  swapOccured  =  true;
    while  (swapOccured)  {
        swapOccured  =  false;
        i++;
        for  (int  j  =  0;  j  < numbers.length -  i;  j++)  {
            if  (numbers[j]  >  numbers[j  +  1])  {
                swap(numbers,  j,  j  +  1);
                swapOccured  =  true;
            }
        }
    }
}

Snippet 2.4: Bubble sort improvement 2

Implement the swap method to swap array elements:

private void swap(int[] numbers, int j, int k) {
    int temp = numbers[j];
    numbers[j] = numbers[k];
    numbers[k] = temp;
}

Code provided:

import java.util.Arrays;

public class BubbleSort {

public void sort(int[] numbers) {
for (int i = 1; i < numbers.length; i++) {
for (int j = 0; j < numbers.length - 1; j++) {
if (numbers[j] > numbers[j + 1]) {
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}

// Write your code here

public static void main(String[] args) {
BubbleSort bubbleSort = new BubbleSort();
int[] numbers = new int[]{2, 5, 7, 2, 4, 2, 8, 1, 0};
int[] numbers2 = new int[]{2, 5, 7, 2, 4, 2, 8, 1, 0};
bubbleSort.sort(numbers);
bubbleSort.sortImprovement2(numbers2);
System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.toString(numbers2));
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program Code to Copy:

import java.util.Arrays;

public class BubbleSort {

    public void sort(int[] numbers) {
        for (int i = 1; i < numbers.length; i++) {
            for (int j = 0; j < numbers.length - 1; j++) {
                if (numbers[j] > numbers[j + 1]) {
                    int temp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = temp;
                }
            }
        }
    }

    //SortImprovement2 method placed here
    public void sortImprovement2(int[] numbers) {
        int i = 0;
        boolean swapOccured = true;
        //If swap becomes false while loop will terminate
        while (swapOccured) {
            swapOccured = false;
            i++;
            for (int j = 0; j < numbers.length - i; j++) {
                if (numbers[j] > numbers[j + 1]) {
                    swap(numbers, j, j + 1);
                    //Making swapOccurred true if a swap has occurred
                    swapOccured = true;
                }
            }
        }
    }

    //Swap method placed here
    private void swap(int[] numbers, int j, int k) {
        int temp = numbers[j];
        numbers[j] = numbers[k];
        numbers[k] = temp;
    }


    public static void main(String[] args) {
        BubbleSort bubbleSort = new BubbleSort();
        int[] numbers = new int[]{2, 5, 7, 2, 4, 2, 8, 1, 0};
        int[] numbers2 = new int[]{2, 5, 7, 2, 4, 2, 8, 1, 0};
        bubbleSort.sort(numbers);
        bubbleSort.sortImprovement2(numbers2);
        //Printing sorted numbers
        System.out.println(Arrays.toString(numbers));
        //Printing sorted numbers using Improvement2 method
        System.out.println(Arrays.toString(numbers2));
    }
}

Output:

Add a comment
Know the answer?
Add Answer to:
Aim To improve the algorithm provided in Snippet 2.3 by reducing the number of passes. public...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Another simple sort is the odd-even sort. The idea is to repeatedly make two passes through the a...

    Another simple sort is the odd-even sort. The idea is to repeatedly make two passes through the array. On the first pass you look at all the pairs of items, a[j] and a[j+1], where j is odd (j = 1, 3, 5, …). If their key values are out of order, you swap them. On the second pass you do the same for all the even values (j = 2, 4, 6, …). You do these two passes repeatedly until...

  • Hello this is my java sorting algorithm program i need all of my errors corrected so...

    Hello this is my java sorting algorithm program i need all of my errors corrected so I can run it. thank you!! import java.util.Scanner;    public class SortingAlogs { public static void main(String[]args){ int array [] = {9,11,15,34,1}; Scanner KB = new Scanner(System.in); int ch; while (true) { System.out.println("1 Bubble sort\n2 Insertion sort\n3 Selection sort\n"); ch = KB.nextInt(); if (ch==1)    bubbleSort(array); if (ch==2)    insertion(array); if (ch==3)    Selection(array); if (ch==4) break;    print(array);    System.out.println(); }    }...

  • Implement the bubble sort algorithm described here: While the array is not sorted For each adjacent...

    Implement the bubble sort algorithm described here: While the array is not sorted For each adjacent pair of elements If the pair is not sorted Swap the elements Use the BubbleSorter class to fill in the code and make it run with the BubbleSorterDemo class. BubbleSorter.java public class BubbleSorter {    /** Sort an integer array using the bubble sort algorithm. @param arr array of integers to sort    */    public static void sort(int[] arr)    { // Your...

  • Below I have done a bubble sort on an array. I need to figure out how...

    Below I have done a bubble sort on an array. I need to figure out how to change the --- bubbleSort() method... with a new method called oddEvenSort() method.. I know I have to do two passes one for odd, one for even, can I have someone help me do this please I keep getting a lot of errors when I attempt to do it. Java code to change is below. I have to sort the array using one pass...

  • import java.util.Arrays; public class lab {    public static void main(String args[])    {    int...

    import java.util.Arrays; public class lab {    public static void main(String args[])    {    int arr[] = {10, 7, 8, 9, 1, 5,6,7};    int arr2[] = {9, 8, 7, 6, 5, 4, 3, 2, 1};    int arr3[] = {1, 3, 5, 3, 2, 6, 20};    quicksort(arr,0,arr.length-1);    quicksort(arr2,0,arr2.length-1);    quicksort(arr3,0,arr3.length-1);    System.out.println(Arrays.toString(arr));    System.out.println(Arrays.toString(arr2));    System.out.println(Arrays.toString(arr3));       }    private static int partition(int[] items,int low, int high)    {    int i=0;    int j=0;...

  • Selection sort is often the first sorting algorithm covered in introductory computer science courses. Java code...

    Selection sort is often the first sorting algorithm covered in introductory computer science courses. Java code that uses selection sort to place the elements of an integer array into non-decreasing order is shown here: public void swapNumbers(int i, int j) { ​int temp = numbers[i];​ /* put numbers[i] somewhere to keep it safe */ ​numbers[i] = numbers[j]; /* put numbers[j] at index i */ ​numbers[j] = temp;​ /* put numbers[i] at index j */ } public void selectionSort(int[] numbers) {...

  • import java.util.Scanner; public class Chpt7_Project {    public static void bubbleSort(int[] list)    {    int...

    import java.util.Scanner; public class Chpt7_Project {    public static void bubbleSort(int[] list)    {    int temp;                       for (int i = list.length - 1; i > 0; i--)    {    for (int j = 0; j < i; j++)    {    if (list[j] > list[j + 1])    {    temp = list[j];    list[j] = list[j + 1];    list[j + 1] = temp;    }    }    }   ...

  • Consider the following function bubbleSort. int bubbleSort(int num[], int numel) {       int i, j, temp,...

    Consider the following function bubbleSort. int bubbleSort(int num[], int numel) {       int i, j, temp, moves = 0;       for (i = 0; i < (numel - 1); i++)       {             for (j = 1; j < numel; j++)             {                   //missing code             }       } } A. Complete the missing code:- (4 Points) B. Assume that the array sort[] which has 8 elements, initially contains the values:- 22 5 67 98 45 32 101 99...

  • Design a program that allows you to experiment with different sort algorithms in Java. This program should allow you to...

    Design a program that allows you to experiment with different sort algorithms in Java. This program should allow you to easily plug-in new sort algorithms and compare them. Assume that input data is generated randomly and stored in a text file (have no less than 2000 items to sort). Do not restrict your program to only one data type, or to one ordering relationship. The data type, ordering relationship, and the sorting method must be input parameters for your program....

  • PLEASE ANSWER #5AND #6, THE ANSWER FOR #3 AND #4 ARE ALREADY PROVIDED!!! 3 .Using Java,...

    PLEASE ANSWER #5AND #6, THE ANSWER FOR #3 AND #4 ARE ALREADY PROVIDED!!! 3 .Using Java, Write a computer program that prompts the user for one number, n for the number of items in the array to sort, and create and sort 1000 arrays of this size timing the run to get an average time to sort an array of this size. Then do the following: Initiate a variable running_time to 0 Create a for loop that iterates 1000 times....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT