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:
Stuart Reges, Marty Stepp
Chapter:
Implementing A Collection Class
Exercise:
Exercises
Question:11 | ISBN:9780136091813 | Edition: 2

Question

Add the following method to the ArrayIntList class from this chapter.

Write a method called printInversions that lists all inversions in a list of integers. An inversion is a pair of numbers in which the first appears before the second in the list, but the first is greater than the second. Thus, for a sorted list such as [1, 2, 3, 4] there are no inversions at all, and the method would produce no output. Suppose that a variable called list stores the values [4, 3, 2, 1] . The call of list.printInversions(); would print many inversions:

(4, 3)

(4, 2)

(4, 1)

(3, 2)

(3, 1)

(2, 1)

The inversions can appear in any order, so this is just one possible correct output. You must reproduce this format exactly, but the inversions can appear in any order. You may assume that the list has no duplicates.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of printInversions method:

	public void printInversions()
	{
		for(int i = 0; i < size - 1; i++)
		{
			for(int j = i + 1; j < size; j++)
			{
				if(elementData[i] > elementData[j])
				{
					System.out.println("(" + elementData[i] 
						+ ", " + elementData[j] + ")");
				}
			}			
		}
	}
0 0

Discussions

Post the discussion to improve the above solution.