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:
Uml And Patterns
Exercise:
Programming Projects
Question:8 | ISBN:9780132830317 | Edition: 5

Question

Redo the QuickSort class to have the modifications given for Programming Projects 12.6 and 12.7.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

//modifications given for Programming Projects 12.6 and 12.7
public class QuickSortDemo
{
	public static void sort(double[] a, int start, int stop) 
	{

		if (stop - start == 1) {
			if (a[start] > a[stop]) {

				double temp = a[start];
				a[start] = a[stop];
				a[stop] = temp;
			}
		} else if (stop - start > 1)
		{
	
			int splitPoint = split(a, start, stop);
			sort(a, start, splitPoint);
			sort(a, splitPoint + 1, stop);
		}
	}

	private static int split(double[] a, int start, int stop)
	{

		double[] temp;

		int size = (stop - start + 1);
		temp = new double[size];
		int middle = (stop + start) / 2;
		double splitValue = a[middle];
		int up = 0;
		int down = size - 1;
		for (int i = start; i < middle; i++) 
		{
			if (a[i] <= splitValue) {
				temp[up] = a[i];
				up++;
			} else {
				temp[down] = a[i];
				down--;
			}
		}
		for (int i = middle + 1; i <= stop; i++)
		{
			if (a[i] <= splitValue)
			{
				temp[up] = a[i];
				up++;
			} else
			{
				temp[down] = a[i];
				down--;
			}
		}

		System.out.println(up + " " + down);
		temp[up] = splitValue;
		for (int i = 0; i < size; i++)
			a[start + i] = temp[i];

		return middle;
	}
	public static void main(String args[]) 
	{
		double[] ele = {1, 2, 6, 4, 3, 7, 10, 24, 25, 26, 19, 17, 30};

		System.out.println("Sorting elements are:");	
		sort(ele, 0, ele.length - 1);
		for (int i = 0; i < ele.length; i++)
			System.out.println(ele[i]);
	}
}

Output of the program:

Sorting elements are:
1.0
2.0
3.0
4.0
6.0
7.0
10.0
17.0
19.0
24.0
25.0
26.0
30.0

 

0 0

Discussions

Post the discussion to improve the above solution.