Question

In: Computer Science

The bubble sort described in AS 7e is inefficient when perform on a larger array. To...

The bubble sort described in AS 7e is inefficient when perform on a larger array. To improve the efficiency, we have to observe the basic mechanism of Bubble Sort.

Each inner loop of the Bubble sort always move the largest item on the unsorted left side to the sorted right side.

When a list is sorted, we say the list is in ascending order by convention.

We can enhance the efficiency of traditional Bubble sort by making only one swapping per inner loop iteration. To accomplish this, the following simple modifications are applied:

  1. The inner loop is to find the index of the largest item inside the unsorted region.
  2. The outer loop is to swap the largest item with the rightmost unsorted item, and then the right most unsorted item becomes the newest sorted item.
  3. The array started as one big unsorted region; each inner loop iteration move one unsorted item to become a sorted item.
  4. The number of comparisons is the same as the standard bubble sort, however, the number of swaps are reduced to no more than once per inner loop and no more than n times for the entire sort.

Hint:
The inner loop finds the index of the largest item of the unsorted region and performs no swap operation.
The outer loop index to track the range of "unsorted region."

Example of Sorted vs Unsorted region through each inner iterations:

4, 3, 5, 7, 2, 9, 1  unsorted | sorted

4, 3, 5, 7, 2, 1| 9 (1st iteration)
4, 3, 5, 1, 2| 7, 9 (2nd iteration)
4, 3, 2, 1| 5, 7, 9 (3rd iteration)
1, 3, 2| 4, 5, 7, 9 (4th iteration)
1, 2| 3, 4, 5, 7, 9 (5th iteration)
1, 2, 3, 4, 5, 7, 9 (6th iteration)

Note:

Complexity of program is to gauge its performance of time and space. See here.

Submit

  • the C++ source code and
  • the test output for self validation

Solutions

Expert Solution

I am using an additional function printArray to print the current order of the array. and also printing the iteration count to show that maximum swappings will be n-1.

*************************************************************************************************************

#include<iostream>
using namespace std;

void printArray(int arr[],int n){
   for(int i=0;i<n;++i){
       cout<<arr[i]<<" ";
   }
   cout<<endl;
}
void bubbleSort(int arr[],int n){
   for(int i=0;i<n-1;++i){
       int index=0; //to store the maximum element in unsorted array
       for(int j=1;j<n-i;++j){
           if(arr[index]<arr[j]){
               index=j;
           }
       }
       int temp=arr[index];
       arr[index]=arr[n-1-i];
       arr[n-1-i]=temp;
       cout<<"Iteration: "<<(i+1)<<endl;
       printArray(arr,n);
   }
}

int main(){
   int arr[]={4, 3, 5, 7, 2, 9, 1};
   int n=7;
   bubbleSort(arr,n);
   cout<<"After sort: ";
   printArray(arr,n);
}

*************************************************************************************************************

You can also reduce the number of swappings by adding another if condition above swapping.

if(index!=n-1-i){

int temp=arr[index];
       arr[index]=arr[n-1-i];
       arr[n-1-i]=temp;

}

This will check whether the largest element is present at right most index of unsorted array or not. if present then no need to swap the elements.

If not present then only swap the elements.

Output:

I would like to share some other modified bubble sort where we can use when the array is partially sorted.

Here the approach is same as above but we will swap the elements in inner loop only. If there won't be any swapping happened in inner loop after some iterations then it means the array is sorted so no need to proceed further and we will simply break the loop.

void bubbleSort(int arr[],int n){
   for(int i=0;i<n-1;++i){
       bool find=true;
       for(int j=0;j<n-1-i;++j){
           if(arr[j+1]<arr[j]){
               int temp=arr[j];
               arr[j]=arr[j+1];
               arr[j+1]=temp;
               find=false;
           }
       }
       if(find)
           break;
   }
}

If you feel it as helpful and shareable share it with your friends.

If you have any doubts kindly ask me. Thank you


Related Solutions

ASSEMBLY PROGRAM!!! QtSpim Sorting Data Add the Bubble Sort to minMaxArray.asm to sort the array into...
ASSEMBLY PROGRAM!!! QtSpim Sorting Data Add the Bubble Sort to minMaxArray.asm to sort the array into ascending order. Use the Bubble Sort algorithm from the lecture. You can use either Base Addressing or Indexed Addressing for the arrays. For this assignment, make sure you prompt the user for the numbers. Do not hard-code them in the data section. NOTE: Declare the array last in the Data section.
// This program uses a bubble sort to arrange an array of integers in // ascending...
// This program uses a bubble sort to arrange an array of integers in // ascending order (smallest to largest). It then display the array // before the sorting and after the sorting. Modify the program so it orders // integers in descending order (largest to smallest). Then add some code // to display the array at each step of the algorithm. You don't have to // modify anything in the main() function. All modification are inside // the bubbleSortArray()...
C++ Program (Using 2D array and bubble sort to sort data) A company pays its salespeople...
C++ Program (Using 2D array and bubble sort to sort data) A company pays its salespeople on a commission basis.  The salespeople each receive $250 per week plus 11 percent of their gross sales for the sales period.  For example, a salesperson who grosses $5000 in sales in the period receives $250 plus 11 percent of $5000, or a total of $812.21.  Write a program (using an array of counters) determines for each salesperson their total sales, their salary and additional data points.  There...
(code in C++ language) [Code Bubble sort, Insertion sort Create a Big array with random numbers....
(code in C++ language) [Code Bubble sort, Insertion sort Create a Big array with random numbers. Record the time. Run Bubble Check time (compute the processing time) do it 100 times (random numbers) Take the average Insertion: Compare] (some explanations please)
1. For each of the following lists, perform a bubble sort, and show the list after...
1. For each of the following lists, perform a bubble sort, and show the list after each exchange: D,B,G,F,A,C,E,H 2. Explain why the bubble sort algorithm does O (n^2) comparisons on an n-element list.
Bubble and Selection Sort For this assignment, you are to consider bubble and selection sort. Both...
Bubble and Selection Sort For this assignment, you are to consider bubble and selection sort. Both are O(n^2) however it may be possible to classify one algorithm as being more efficient than the other. You are to discuss which algorithm you feel is the most efficient and in what cases it will be more efficient. Provide any relevant test cases and code to support your belief. Submit a pdf containing your findings and test results along with any relevant code...
Given the following array [17, 15,21,208,16,122,212,53,119,43] Apply bubble sort algorithm and show the status of the...
Given the following array [17, 15,21,208,16,122,212,53,119,43] Apply bubble sort algorithm and show the status of the array after each pass. Also calculate how many comparisons you will be required to pass
For the given array, simulate the working operation of Bubble Sort. Show your work at each...
For the given array, simulate the working operation of Bubble Sort. Show your work at each step. Make sure to show the status of the array after every swap. [ 28, 13, 22, 7, 34, 2 ]
5. (20 marks) Write a recursive Bubble Sort algorithm that takes an array A of n...
5. Write a recursive Bubble Sort algorithm that takes an array A of n numbers as input. Analyze its time complexity using a recursion tree. Implement your algorithm in Java
How would I make a bubble sort and an optimized bubble sort with the code given?...
How would I make a bubble sort and an optimized bubble sort with the code given? I also need to implement a timer into each sort and display runtime with the sorts. NODE.H _______________________________________________________________________________________________________ /* node.h */ /* two classes 1: node.h 2. singlylinkedlist.h nod1 (value + pointer) ---> node2 ---> node3 ---> |||| <--- node.h ^ | singlylinkedlist ----------------*node head; */ #ifndef NODE_H #define NODE_H #include <iostream> using namespace std; class Node {    friend class singlyLinkedList; public:   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT