SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Arrays
Exercise:
Programming Projects
Question:8 | ISBN:9780132830317 | Edition: 5

Question

Design a class called BubbleSort that is similar to the class SelectionSort given in Display 6.11. The class BubbleSort will be used in the same way as the class SelectionSort, but it will use the bubble sort algorithm.

The bubble sort algorithm checks all adjacent pairs of elements in the array from the beginning to the end and interchanges any two elements that are out of order. This process is repeated until the array is sorted. The algorithm is as follows:

Bubble Sort Algorithm to Sort an Array a

Repeat the following until the array a is sorted:

for (index = 0; index < a.length – 1; index++)

if (a[index] > a[index + 1])

Interchange the values of a[index] and a[index + 1].

The bubble sort algorithm is good for sorting an array that is “almost sorted.” It is not competitive with other sorting methods for most other situations.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

public class Main 
{
    public static void main(String args[])
	{
        int[] elements = { 159, 77, 543, 38, 19, 115, 93};
		System.out.println("Un-sorted array elements are:");
		for(int i = 0; i < elements.length; i++)
			System.out.print(elements[i] + " ");
    		System.out.println();
		BubbleSort sorter = new BubbleSort();
		sorter.sort(elements);
		System.out.println("\nAscending sorted array elements by using bubble sort:");
		for(int i = 0; i < elements.length; i++)
		System.out.print(elements[i] + " ");		
	}
}
   class BubbleSort 
    {
    	public void sort(int[] index)
    	{
        for(int outer = index.length - 1; outer > 0; outer--)
	     {
			for(int inner = 0; inner < outer; inner++)
			{
				if(index[inner] > index[inner + 1])
				{
					int temp = index[inner];
					index[inner] = index[inner + 1];
					index[inner + 1] = temp;
				}
			}
		}

	}
}

Output of the program:

Un-sorted array elements are:
159 77 543 38 19 115 93 

Ascending sorted array elements by using bubble sort:
19 38 77 93 115 159 543 

 

0 0

Discussions

Post the discussion to improve the above solution.