Question

Write a JAVA Program: Compare the performance of bubble sort and selection sort over several arrays....

Write a JAVA Program:

Compare the performance of bubble sort and selection sort over several arrays.

- Write two methods that sort arrays of doubles. One method should use selection sort, and the other should use bubble sort.

- In each of the sort methods, add code that counts the total number of comparisons and total number of swaps performed while sorting the entire array (be careful; don't count each pass through the array separately)

- Each time an array is sorted, print out the name of the algorithm used (selection or bubble), the number of comparisons, and the number of swaps. You may print these out from within the sort function; you do not need to figure out how to pass these values back to main()

- In main(), create several arrays and run the sort algorithms for each of them. Include one array that is already sorted, one that is sorted in descending order, one that has no obvious order, and one or two other ones that use whatever patterns you think are interesting.

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

Hi Dear,

Please find my basic implementation.

import java.util.Random;

public class SortComparisons

{
    public static void selectionSort(int arr[])
    {
        int n = arr.length;

        int comparison = 0;

        int swaps = 0;
        // One by one move boundary of unsorted subarray
        for (int i = 0; i < n-1; i++)
        {
            // Find the minimum element in unsorted array
            int min_idx = i;
            for (int j = i+1; j < n; j++) {
                comparison++;
                if (arr[j] < arr[min_idx])
                    min_idx = j;
            }

            // Swap the found minimum element with the first
            // element
            int temp = arr[min_idx];
            arr[min_idx] = arr[i];
            arr[i] = temp;

            swaps++;
        }

        System.out.println("Selection Sort: ");
        System.out.println("\tComparisons : " + comparison);

        System.out.println("\tSwaps : " + swaps);
    }

    // function to sort array a using bubble sort

    public static void bubble_sort(int a[])
    {
        int i, j, x;
        int comparison = 0;
        int swaps = 0;


        for( i = 0 ; i < a.length - 1 ; i++)
        {
            for( j = 0 ; j < a.length - i - 1 ; ++j)
            {
                // increment the comparison count
                comparison++;

                if (a[ j + 1 ] < a[ j ])
                {
                    // increment the swap count
                    swaps++;
                    // swap the j and j + 1 th element of a

                    x = a[j];

                    a[ j ] = a[ j + 1 ];

                    a[ j + 1 ] = x;

                }

            }

        }


        System.out.println("Bubble Sort: ");
        System.out.println("\tComparisons : " + comparison);
        System.out.println("\tSwaps : " + swaps);

    }



    public static void main(String args[])

    {

        //Create test array

        int[] test = new int[100];
        int[] test1 = new int[100];

        Random rand = new Random();

        for(int i=0; i<test.length; i++) {
            int r = rand.nextInt(1000);//0 - 999
            test[i] =  r;
            test1[i] =  r;
        }


        //Sort it - Students replace this with your sort (bubble, merge, or quick)

        bubble_sort(test);

        selectionSort(test1);
    }

}

Output:

Bubble Sort:

Comparisons : 4950

Swaps : 2337

Selection Sort:

Comparisons : 4950

Swaps : 99

Process finished with exit code 0

Please DONT forgot to rate my answer. We are working hard for you Guys!!

Add a comment
Answer #2
import java.util.Random; 
public class SortComparisons { 
public static void selectionSort(int arr[]) 
{ 
int n = arr.length;
 int comparison = 0;
  int swaps = 0; 
  for (int i = 0; i < n-1; i++) { 
   int min_idx = i;
    for (int j = i+1; j < n; j++) {
     comparison++;
      if (arr[j] < arr[min_idx]) 
      min_idx = j; 
      } // 
       int temp = arr[min_idx]; 
       arr[min_idx] = arr[i]; 
       arr[i] = temp; 
       swaps++; 
       } 
   System.out.println("Selection Sort: ");
   System.out.println("\tComparisons : " + comparison); 
   System.out.println("\tSwaps : " + swaps); } 
public static void bubble_sort(int a[]) { 
int i, j, x; 
int comparison = 0; 
int swaps = 0; 
for( i = 0 ; i < a.length - 1 ; i++) { 
for( j = 0 ; j < a.length - i - 1 ; ++j) { 
comparison++; 
if (a[ j + 1 ] < a[ j ]) { 
 swaps++;  
 x = a[j]; 
 a[ j ] = a[ j + 1 ]; 
 a[ j + 1 ] = x; 
 } 
 }
} 
System.out.println("Bubble Sort: "); 
System.out.println("\tComparisons : " + comparison); 
System.out.println("\tSwaps : " + swaps); 
} 
public static void main(String args[]) { 
 int[] test = new int[100]; 
 int[] test1 = new int[100]; 
 Random rand = new Random(); 
 for(int i=0; i<test.length; i++) { 
 int r = rand.nextInt(1000);//0 - 999 
 test[i] = r; 
 test1[i] = r; 
}  
bubble_sort(test); 
selectionSort(test1); 
} 
}


answered by: Shivani Sharma
Add a comment
Know the answer?
Add Answer to:
Write a JAVA Program: Compare the performance of bubble sort and selection sort over several arrays....
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
  • Write a java program to sort arrays using 3 different methods: Bubble Sort, Selection Sort and...

    Write a java program to sort arrays using 3 different methods: Bubble Sort, Selection Sort and Insertion Sort. The numbers to be sorted will be obtained using a library function which generates pseudo-random numbers. TO Do 1. Fill an array with 140 real numbers between 0.00 and 945.00. Generate the numbers using the subroutine that generates random numbers. Make a spare copy of the array; you will need it later. 2. Call a subroutine to print the contents of the...

  • This program should test the running time of these algorithms: Selection Sort Insertion Sort Bubble Sort...

    This program should test the running time of these algorithms: Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort Heap Sort You have access to the implementation of all of these sorting algorithms, and you may use what is provided in your text directly. Be sure to cite the source of these implementations in the header of your program. Please maintain the property that these sorting algorithms sort arrays in ascending order. For this homework, you will write a...

  • C++ Search & Sort

    Exercise #2: Design and implement a program (name it SimpleSort) to implement and test the three sort algorithms (Bubble, Insertion, Selection) discussed in the lecture slides.  Define method BubbleSort() to implement Bubble sort of an array of integers. Modify the algorithm implementation to count number of swaps it takes to sort the array.  Define method InsertionSort() to implement insertion sort of an array of integers. Modify the algorithm implementation to count number of swaps it takes to sort the array. Define...

  • Write in C++ (Bubble Sort) implement the bubble sort algorithm - another simple yet inefficient s...

    Write in C++ (Bubble Sort) implement the bubble sort algorithm - another simple yet inefficient sorting technique. its called bubble sort or sinking sort because smaller values gradually "bubble" their way to the top of the array like air bubbles rising in water, while the larger values sink to the bottom of the array. the technique uses nested loops to make several passes through the array. each pass compares successive pairs of elements. if a pair is in increasing order,...

  • Write a program that compares the execution speed of two different sorting algorithms: bubble sort and...

    Write a program that compares the execution speed of two different sorting algorithms: bubble sort and selection sort. It should do this via functions you must write with the following prototypes: void setRandomValues(int[], int[], int length); This function sets two integer arrays with identical random values. The first two arguments are two integer arrays of the same length, and the third argument is the length of those arrays. The function then sets each element in the first and second argument...

  • Implement and compare sorting algorithms. The task is to sort a list of integers using 5...

    Implement and compare sorting algorithms. The task is to sort a list of integers using 5 sorting algorithms: selection sort insertion sort merge sort heap sort quicksort Your program should include 5 separate sorting methods, though it is fine for them to call some common methods (like "swap") if needed. Each sorting method should also count the number of comparison operations and assignment operations on the array elements during the sorting process. In the main program, two types of array...

  • C programming Strictly - Write a program to sort an array of integers via arrays of...

    C programming Strictly - Write a program to sort an array of integers via arrays of pointers to those integers as shown in the figure. Problem 1 (68 points): Write a program to sort an array of integers via arrays of pointers to those integers as shown in the figure. The code should contain the following functions: 1)to randomly generate an array of integer numbers; 2) to allocate memory and build the arrays of pointers as shown in the figure...

  • Need help with program. I'm stuck Objectives: In this assignment, we will practice manipulating lists of...

    Need help with program. I'm stuck Objectives: In this assignment, we will practice manipulating lists of data and arranging items in an ascending/descending order. you will also explore storing lists/arrays using different sorting algorithms including, the selection sort, bubble sort, and insertion sort algorithm. Comparison between the three algorithms are made based on the number of comparisons and item assignments (basic operations) each algorithms executes. Background: Ordering the elements of a list is a problem that occurs in many computer...

  • 1. Write a Java program to implement Counting Sort and write a driver to test it....

    1. Write a Java program to implement Counting Sort and write a driver to test it. Note: use random number generator to generate your input with n = 10, 50, and 100. Verify that the running time is O(n). 2. Write a Java program to implement Bucket Sort and write a driver to test it. Note: use random number generator to generate your input with n = 10, 50, and 100. Verify that the running time is O(n). 3. In...

  • 11:10 PM No SIM mycourselink.lakeheadu.ca Modify the following bubble sort program to improve its performance I...

    11:10 PM No SIM mycourselink.lakeheadu.ca Modify the following bubble sort program to improve its performance I Fig. 6.15: fig06 15.c 2 Sorting an array's values into ascending order. Finclude <stdio.h> 4 #define SIZE 10 6 function main begins program execution 7 int main(void) 9 initialize a lo int a CSIZEJ 12, 6, 4, 8, 10, 12, 89, 68, 45, 37) 12 putsc Data items in original order output original array IS for (size t i 0; i SIZE ++i) a[i])...

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
ADVERTISEMENT