package template7; import java.util.*; public class TemplatesMain { /** * @param
ID: 3618626 • Letter: P
Question
package template7;
import java.util.*;
public class TemplatesMain
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
List<Product> list = new ArrayList<Product>();
List<Product> tempList = new ArrayList<Product>();
list.add(new Product(1, "Maud"));
list.add(new Product(8, "Ashley"));
list.add(new Product(4, "Kingdom"));
list.add(new Product(3, "Cad"));
list.add(new Product(5, "James"));
int l = 0, r = list.size() - 1;
mergesort(list, tempList, l, r);
Product product = null;
for(int i=0;i<list.size();i++)
{
product =(Product) list.get(i);
product.display();
}
System.out.printf(" ");
Collections.sort(list);
for(int i=0;i<list.size();i++)
{
product =(Product) list.get(i);
product.display();
}
}
private static void mergesort(List<Product> list, List<Product> tempList, int leftIndex, int rightIndex)
{
int midIndex, nItems;
nItems = rightIndex - leftIndex + 1;
if(nItems == 1)
return;
midIndex = (rightIndex + leftIndex) / 2;
mergesort(list, tempList, leftIndex, midIndex);
mergesort(list, tempList, midIndex + 1, rightIndex);
merge(list, tempList, leftIndex, midIndex+1, rightIndex);
return;
}
private static void merge(List<Product> itemsList, List<Product> tempList, int leftIndex, int midIndex, int rightIndex)
{
int leftEnd, nItems, tempsIndex;
leftEnd = midIndex - 1;
tempsIndex = leftIndex;
nItems = rightIndex - leftIndex + 1;
while((leftIndex <= leftEnd) && (midIndex <= rightIndex))
{
if(itemsList.get(leftIndex).compareTo(itemsList.get(midIndex)) <= 0)
{
tempList.add(tempsIndex, itemsList.get(leftIndex));
tempsIndex = tempsIndex + 1;
leftIndex = leftIndex + 1;
}
else
{
tempList.add(tempsIndex, itemsList.get(midIndex));
tempsIndex = tempsIndex + 1;
midIndex = midIndex + 1;
}
}
if(leftIndex <= leftEnd)
{
while(leftIndex <= leftEnd)
{
tempList.add(tempsIndex, itemsList.get(leftIndex));
leftIndex = leftIndex + 1;
tempsIndex = tempsIndex + 1;
}
}
else
{
while(midIndex <= rightIndex)
{
tempList.add(tempsIndex, itemsList.get(midIndex));
midIndex = midIndex + 1;
tempsIndex = tempsIndex + 1;
}
}
for(int i=0;i < nItems; i++)
{
itemsList.set(rightIndex, tempList.get(rightIndex));
rightIndex = ri
Explanation / Answer
x.Hava.util.ArrayList; import java.util.Collections; import java.util.List; public class TemplatesMain { public static void main(String[] args) { List list = new ArrayList(); List tempList = new ArrayList(); list.add(new Product(1, "Maud")); list.add(new Product(8, "Ashley")); list.add(new Product(4, "Kingdom")); list.add(new Product(3, "Cad")); list.add(new Product(5, "James")); int l = 0, r = list.size() - 1; mergesort(list, tempList, l, r); Product product = null; for(int i=0;iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.