Java Recursive Merge Sort - java

Currently am struck on my recursive merge sorting program, I have been looking to see where the problem is and i cant seem to find it.
package mergesort;
import java.util.ArrayList;
public class MergeSort {
public MergeSort() {
// TODO Auto-generated constructor stub
}
public static <T extends Comparable<? super T>> void mergesort(T[] list, int n)
{
mergeSort(list,0,n-1);
}
static <T extends Comparable<? super T>>
void mergeSort(T[] tempArray, int firstHalfSorted, int secondHalfSorted){
T[] temp = (T[]) new Comparable <?>[tempArray.length];
mergeSort(tempArray, temp, firstHalfSorted, secondHalfSorted);
}
private static <T extends Comparable<? super T>>
void mergeSort (T[ ] tempArray, T[] a, int firstHalfSorted, int secondHalfSorted){
if (firstHalfSorted < secondHalfSorted)
{
int mid = (firstHalfSorted + secondHalfSorted) / 2;
mergeSort(tempArray,a,firstHalfSorted, mid);
mergeSort(tempArray,a,mid+1, secondHalfSorted);
if(tempArray[mid].compareTo(tempArray[mid+1])>0)
merge(tempArray,a,firstHalfSorted, mid, secondHalfSorted);
}
}
private static <T extends Comparable<? super T>>
void merge(T[] a, T[] tempArray, int firstHalfSorted, int mid, int secondHalfSorted)
{
int bhalf1 = firstHalfSorted;
int ehalf1 = mid;
int bhalf2 = mid + 1;
int ehalf2 = secondHalfSorted;
int j = 0;
for(;(bhalf1 <= ehalf1) && (bhalf2 <= ehalf2); j++)
{
if (a[bhalf1].compareTo(a[bhalf2]) < 0)
{
tempArray[j] = a[bhalf1];
bhalf1++;
}
else
{
tempArray[j] = a[bhalf2];
bhalf2++;
}
for(;bhalf1 <= ehalf1; bhalf2++, j++)
tempArray[j] = a[bhalf1];
for(;bhalf2 <= ehalf2; bhalf2++, j++)
tempArray[j] = a[bhalf2];
for(j = firstHalfSorted; j <= secondHalfSorted; j++)
a[j] = tempArray[j];
}
}
}
here is the sample of what should be happening
Before sort:
Zeke
Bob
Ali
John
Jody
Jamie
Bill
Rob
Zeke
Clayton
After sort:
Ali
Bill
Bob
Clayton
Jamie
Jody
John
Rob
Zeke
Zeke
also my main driver i made is here also
package mergesort;
import java.util.ArrayList;
import java.util.Arrays;
public class Driver <T extends Comparable<? super T>>{
public Driver() {
// TODO Auto-generated constructor stub
}
public static <T> void main(String[] args) {
String array[] = new String[] {"Zeke,"Bob","Ali","John","Jody","Jamie","Bill","Rob", "Zeke", "Clayton"};
MergeSort sortList = null;
sortList.mergeSort(array,0,10);
for(int a=0;a<array.length;a++)
System.out.println(array[a]);
}
}

Your merge method has many problems.
Take every for loop in there and write a 1-line comment describing what it's supposed to do.
Do not declare a variable (like j) and then reuse it for multiple loops. Confine the loop variable to the loop scope, e.g. for (int j = ..; .. ; ..).
Correct your indentation and make sure that the nested loops were really meant to be nested.
Write a few test cases for merge method and test just that method separately from all the recursion.

Related

MergeSort doesn't work in my code

I tried to implement the MergeSort, but it doesn't display the right order of the number. I want to see what happened in my code and how to fix it properly.
public class MergeSort {
private static void sort(int[]a,int start,int end){
if(start>=end){return;}
int halfway=(start+end)/2;
sort(a,start,halfway);
sort(a,halfway+1,end);
//now that the halves are sorted
int []scratch=new int[end-start+1];
int g1=start,g2=halfway+1;//i is the next inedex in the first half to consider
//j is the next index in the second half to consder
//k is the next index to populating in the scrach arry
for(int p=0;p<=scratch.length;p++){
if(a[g1]<a[g2]){
scratch[p]=a[g1];g1++;//smaller one is a[i]
if(g1>=halfway){break;}
}
else {scratch[p]=a[g2];
g2++;
if (g2>=end){break;}
}
if(g1>halfway+1){
scratch[p]=a[g2];
g2++;
}
if(g2>end+1){
scratch[p]=a[g1];
g1++;
}
scratch=a;
}
}
public static void sort(int[]a)
{
sort(a,0,a.length-1);
}
public static void main(String[] args){
int[] starter={2,1,3,5,6,7,8};
sort( starter);
for(int i=0;i<starter.length;i++){
System.out.print(" "+starter[i]);
}
}
}
//if first stack is empty then you grab the next one,
//if get1 pass to the stopat1(mid+1),then it need to copy the rest of the number,the rest of number are being sorted
//It also apply at get2 as well.
You can read java.util.Collections.sort(starter);
public static <T extends Comparable<? super T>> void sort(List<T> list) {
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator<T> i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set((T)a[j]);
}
}

Java Generics Bound mismatch

Here is a implementation of a generic search algorithm:
The interface:
public interface Comparable<T extends Comparable<T>> {
int compare(T arg);
}
CompareSort.java
public abstract class CompareSort<T extends Comparable<T>> {
protected boolean less(T v, T w) {
return (v.compare(w) < 0);
}
protected void swap(T[] args, int i, int j) {
T swap = args[i];
args[i] = args[j];
args[j] = swap;
}
public abstract void sort(T[] args);
}
One of the algorithm:
public class SelectionSort <T extends Comparable<T>> extends CompareSort<T> {
#Override
public void sort(T[] args) {
int N = args.length;
for (int i = 0; i < N; i++) {
int min = i;
for (int j = i + 1; j < N; j++) {
if (less(args[j], args[min])) {
min = j;
}
}
swap(args, i, min);
}
}
}
And finally a main method to sort Strings.
public class StringSorter {
public static <T extends Comparable<T>> void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<String>();
int i = 0;
while (i < 10) {
Scanner s = new Scanner(System.in);
String str = s.nextLine();
list.add(str);
i++;
}
String[] a = list.toArray(new String[list.size()]);
// Create a sort object, use it on a, and print the sorted array.
SelectionSort<String> selection = new SelectionSort<String>();
selection.sort(a);
for (i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
Here is the problem:
SelectionSort<String> selection = new SelectionSort<String>();
Bound mismatch: The type String is not a valid substitute for the bounded parameter (T extends Comparable(T)) of the type SelectionSort(T)
(box brackets = curved brackets)
Where is the problem? I can not figure it out...
the generic parameter T is extended as well.
Instead of creating your own Comparable, which String does not implement, use Java's java.lang.Comparable, which String does implement.

Sorting algorithms - how to implement my classes in main :)

It's silly problem. I have my own comparator interface, class Student - it's objects will be sorted, class BubbleSort with bubblesorting algorithm and main. I think every class except from main is written quite well, but I have problem with implementation of them in main to make my sorting to start :/ I've just created ArrayList of random Students I want to be sorted, but I have problem with BubbleSort class and have no idea, how to start.
In future (I hope it will be today :)) I will do exactly the same with another classes containing sorting algorithms like BubbleSort here. I think their implementation in main will be identical.
import java.util.Random;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
int elements = 100000;
ArrayList<Student> list = new ArrayList<Student>();
Random rand = new Random();
for (int i=0; i<elements; i++) {
list.add(new Student(rand.nextInt(4)+2, rand.nextInt(900000)));
}
System.out.println(list);
}
}
.
import java.util.ArrayList;
public class BubbleSort {
private final Comparator comparator;
public BubbleSort(Comparator comparator) {
this.comparator = comparator;
}
public ArrayList<Student> sort(ArrayList<Student> list) {
int size = list.size();
for (int pass = 1; pass < size; ++pass) {
for (int left = 0; left < (size - pass); ++left) {
int right = left + 1;
if (comparator.compare(list.get(left), list.get(right)) > 0)
swap(list, left, right);
}
}
return list;
}
public int compare(Object left, Object right) throws ClassCastException
{ return comparator.compare(left, right); }
private void swap(ArrayList list, int left, int right) {
Object temp = list.get(left);
list.set(left, list.get(right));
list.set(right, temp);
}
}
.
public class Student implements Comparator<Student> {
int rate;
int indeks;
public Student(int ocena, int index) {
this.rate = ocena;
indeks = index;
}
public String toString() {
return "Numer indeksu: " + indeks + " ocena: " + rate + "\n";
}
public int getIndeks() {
return indeks;
}
public int getRate() {
return rate;
}
public int compare(Student left, Student right) {
if (left.getIndeks()<right.getIndeks()) {
return -1;
}
if (left.getIndeks() == right.getIndeks()) {
return 0;
}
else {
return 1;
}
}
}
.
public interface Comparator<T> {
public int compare(T left, T right) throws ClassCastException;
}
Your code looks little bit strange. You didnt mention if you have to use bubble sort so i write both my ideas
1.Without explicitly using bubble sort
You can use Collections.sort() combined with overridencompareTo() method
So your code will look like this
class Student implements Comparable<Student>{
//variables constructor methods go here
private index;
#Override
public int compareTo(Students s) {
int index = s.index;
if (this.index > index) {
return 1;
} else if (this.index == index) {
return 0;
} else {
return -1;
}
}
}
And in your main class Collections.sort(myStudents)
2.Explicitly using bubble sort
Student class
class Student{
//class variables methods constructor goes here
}
Comparator class
class StudentComparator implements Comparator<Student>{
#Override
public int compare(Student a, Student b) {
//bubble sort code goes here
}}
Main class
class MyMainClass{
public static void main(String[] args) {
public int elements = 100000;
ArrayList<Student> list = new ArrayList<Student>();
Random rand = new Random();
for (int i=0; i<elements; i++) {
list.add(new Student(rand.nextInt(4)+2, rand.nextInt(900000)));
}
Collections.sort(list, new StudentComparator());
}
Two points to make here:
a) You are not calling sort at all. You need to instantiate your BubbleSort class and actually call the method. list = new BubbleSort(new Comparator(){...}).sort(list); <-- This syntax also calls for the sort method to be static so that you don't need to make a new object for every sort. The example below sorts by index.
list = new BubbleSort(new Comparator<Student>() {
#Override
public compare(Student a, Student b) {
return a.getIndeks() - b.getIndeks();
}
}).sort(list);
Btw, this also assumes that BubbleSort is made generic, since it's easier (and kinda makes sense anyway)
b) I hope this is some kind of project where you have to show your ability to make a sorting algorithm, otherwise you should use library methods for these things
Also, while the code is not bad, you might want to show it to someone with professional Java experience (it does not conform to a lot of standards and many things can be improved and made consistent with each other), or post it to https://codereview.stackexchange.com/
I dont see you calling the bubblesort class anywhere. A list will not automatically sort its elements. Please go through this link. You ll find it handy.
http://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/

compareTo with generics for heapSort

For class I had to either implement a BST or a heapSort. I did the BST but figured it would be good to know this too but now I'm stuck. This is my first time working with heaps(and really coding with generics/implementing Comparable so I apologize for all the errors) and im running into an issue implementing compareTo.
Essentially I want to be able to add generic objects to my heap Array and then compare them for the Heap sorting. I use compareTo to check a new entry when adding to the heap and for swapping in the reheap method.
My errors returned:
Heap.java:64: error: bad operand types for binary operator '<'
if (this < other)
^
first type: Heap<T>
second type: Heap<T>
where T is a type-variable:
T extends Comparable<T> declared in class Heap
Im not sure how to work around that though. I understand that my binary operator isnt for generics but I dont know how to work around it.
Thanks for any input. Sorry about all the beginners mistakes you may find!
Heres my code:
import java.util.*;
class Heap<T extends Comparable <T>> implements Comparable<Heap<T>>{
private T[] heap;
private int lastIndex;
private static final int CAPACITY = 25;
public Heap(){
this(CAPACITY);
}
public Heap(int capacity){
heap = (T[])new Comparable[capacity+1];
lastIndex = 0;
}
public void add(T newEntry){
lastIndex++;
if(lastIndex>=heap.length)
doubleArray();
int newIndex = lastIndex;
int parentIndex = newIndex/2;
while((parentIndex>0)&&(heap[parentIndex].compareTo(newEntry)>0))
{
heap[newIndex] = heap[parentIndex];
newIndex = parentIndex;
parentIndex = newIndex/2;
}
heap[newIndex] = newEntry;
}
public void display()
{
for(int i=1;i<heap.length;i++)
{
System.out.println(heap[i]);
}
}
private void doubleArray()
{
T[] oldHeap = heap;
int oldSize = heap.length;
heap = (T[]) new Object[2*oldSize];
for(int i =0; i < oldSize-1;i++)
{
heap[i] = oldHeap[i];
}
}
public int compareTo(Heap<T> other)
{
int sort = 0;
if (this < other)
{
sort = -1;
}
else if (this> other)
{
sort = 1;
}
else
{
sort = 0;
}
return sort;
}
private <T extends Comparable<T>> void reheap(T[] heap, int rootIndex, int lastIndex)
{
boolean done=false;
T orphan = heap[rootIndex];
int leftChildIndex = 2 * rootIndex + 1;
while(!done && (leftChildIndex<=lastIndex))
{
int largerChildIndex = leftChildIndex;
int rightChildIndex = leftChildIndex + 1;
if(rightChildIndex<=lastIndex && (heap[rightChildIndex].compareTo(heap[largerChildIndex])>0))
largerChildIndex = rightChildIndex;
if(orphan.compareTo(heap[largerChildIndex])<0)
{
// System.out.println(orphan+ "--" + largerChildIndex);
heap[rootIndex] = heap[largerChildIndex];
rootIndex = largerChildIndex;
leftChildIndex = 2 * rootIndex+1;
}
else
done = true;
}
heap[rootIndex] = orphan;
}
public <T extends Comparable<T>> void heapSort(int n)
{
for(int rootIndex = n/2-1;rootIndex >=0;rootIndex--)
reheap(heap,rootIndex,n-1);
swap(heap,0,n-1);
for(int lastIndex = n-2;lastIndex > 0;lastIndex--)
{
reheap(heap,0,lastIndex);
swap(heap,0,lastIndex);
}
}
private <T extends Comparable<T>> void swap(T[] a,int first, int last)
{
T temp;
temp = a[first];
a[first] = a[last];
a[last] = temp;
}
}
Any help with any of this is very very appreciated
You don't want your heap to be Comparable; you want to compare its members. Therefore remove implements Comparable<Heap<T>> from your class declaration and remove the compareTo method.
Many of your methods (reheap, heapSort, swap) redundantly declare <T extends Comparable<T>> where you are already in the context of your class parameterized with T. Remove those declarations.
I think you need to implement the compareTo on you T object, not on the heap itself. You have to
make sure T is comparable for it to be in the heap.

Generics in Java: How do I make this example work?

class main{
public static void main(String[] args){
int[] array = new int[3];
array[0]=3;
array[1]=2;
array[2]=1;
System.out.println(<Integer>countGreaterThan(array,1));
}
static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
}
I got this examle in Java Documentation. When i write extends Comparable, how can i tell the compiler what is type?
I think i should instantiate T in <T extends Comparable<T>>, but how?
Just change the int to Integer and remove that ugly <Integer> inside your print statement.
Integer[] array = new Integer[3];
array[0] = 3;
array[1] = 2;
array[2] = 1;
System.out.println(countGreaterThan(array, 1));
I would arrange this so you can use varargs
static <T extends Comparable<T>> int countGreaterThan(T elem, T... anArray) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
}
System.out.println(countGreaterThan(1, 3,2,1));
class main {
public static void main(String[] args){
Integer[] array = new Integer[3];
array[0]=3;
array[1]=2;
array[2]=1;
System.out.println(countGreaterThan(array,1));
}
static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
}
Integer[] array = new Integer[3];
array[0]=3;
array[1]=2;
array[2]=1;
System.out.println(countGreaterThan(array,1));
Is this what you are looking for?

Categories