MergeSort doesn't work in my code - java

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]);
}
}

Related

Inserting into a simple Array and Deleting

public class DataOperations {
int arraySize=50;
int[]array=new int[arraySize];
public void generateRandomArray(){
for(int i=0;i<arraySize;i++){
array[i]=i;
}
}
public int getValueAtIndex(int index){
if(index<arraySize){
System.out.println("Your value At index "+index+" is "+array[index]);
return array[index];
}else{
System.out.println("Please Return an Index that is inbounds");
return 0;
}
}
public boolean doesArrayContainValue(int searchValue){
boolean valueInArray=false;
for(int i=0;i<arraySize;i++){
if(array[i]==searchValue){
valueInArray=true;
}
}
return valueInArray;
}
public void deleteIndex(int index){
if(index<arraySize){
for(int i=index;i<(arraySize-1);i++){
array[i]=array[i+1];
}
}
System.out.println(arraySize);
arraySize--;
System.out.println(arraySize);
}
public void printArray(){
for(int i=0;i<arraySize;i++){
System.out.print(i+"-");
System.out.println(array[i]);
}
}
public void insertValue(int index){
if(index<arraySize){
array[arraySize]=index;
System.out.println(arraySize);
arraySize++;
System.out.println(arraySize);
}
}
public void linearSearchForValue(int value){
boolean valueInArray=false;
System.out.println("The was Found and is at Index:");
for(int i=0;i<arraySize;i++){
if(array[i]==value){
System.out.println(i);
}
}
}
}
Hey So I created simple add and delete methods to my array. However, I am unsure about a couple parts. I Understand the add method, and that we are decreasing the arraySize from 50 to 49 for this specific array object that I created in my Driver class below. However, I am not sure why I cannot do my add method before my delete method insertValue method if I put arraySize++ before array[arraySize]=index, and did not call my deleteIndex method shouldnt my arraySize=51? but this throws an out of bounds exception
Driver Class Below
public class Driver {
public static void main(String[] args) {
DataOperations array=new DataOperations();
array.generateRandomArray();
array.insertValue(20);
array.printArray();
}
}
int arraySize=50;
You create an array of size 50. Arrays are of fixed size hence you cannot get an array of size 51. In your code, when adding/deleting an element from the array, you arent changing the size of the array. You are just moving the index to get your desired output. If you want a bigger array you can:
Create a new array of required size and copy all elements from old to new
Use ArrayList instead of arrays.

Java Recursive Merge Sort

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.

Return element at position index. (No ArrayList)

format: get(index):Object.
public class MyArrayList {
public String[] arrays = {};
public MyArrayList() {
arrays = new String[10];
}
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
}
public class MyArrayListTest {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.size() + " animals: ");
for (int j = 0; j < zoo.size(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("Testing constructor, add(object) and size() ");
zoo.add("Ant");
zoo.add("Bison");
zoo.add("Camel");
zoo.add("Dog");
zoo.add("Elephant");
zoo.add("Frog");
zoo.add("Giraffe");
zoo.add("Horse");
printZoo();
System.out.println();
}
}
With this code it prints out:
Testing constructor, add(object) and size()
The zoo now holds 10 animals: 0 1 2 3 4 5 6 7 8 9
Obviously my code for get method is very wrong but instead of printing out the numbers it should print out "Ant","Bison,"Camel" etc.
All help appreciated for code as I'm a very new programmer. Thanks.
Fixing your Get Method
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
}
Okay, so let's look at this shall we? There's a few values that the user can provide..
i < 0
0 < i < size of array <-- The only valid one.
i > size of array
So first you need to check for that!
if(i > 0 && i < arrays.length) {
// This is a valid index!
}
Okay, so you know it's a valid index. Step two is retrieving the value..
return arrays[i];
And finally, the return type needs to be set. At the moment it is int. It needs to be String in this example..
public String get(int i)
It's that simple! When you call printZoo(), you'll see the values and not their indices.
Onto your Objects
You can have an array of type Object without importing any classes. This will change arrays of type String[] to..
Object[] arrays;
Your Code is technically correct, but if you want to return string values in run time, you must change the value returned in method get to String as in
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
to
public String get(int i){
return arrays[i];
}
Also in your method printZoo(), you have another loop, so i'd imagine your code printing out duplicate values. so why don't you have the printZoo Method dealing with the for loop and the get() method above displaying the values
So Change your get method to the one i have here, and everything should work for you
If it doesn't Work, then try these pieces of Code
MyArrayList.java
public class MyArrayList{
public String[] arrays = {};
public int i = 0;
public MyArrayList() {
arrays = new String[10];
}
public void add(String a)throws ListFullException{ //Add to List if Arraylist is not full
if(i != arrays.length-1){
arrays[i] = a;
i++;
}
else{
throw new ListFullException("List Full");
}
}
public String get(int i){
return arrays[i];
}
public int getArraySize(){
return arrays.length;
}
}
MyArrayListTest.java
public class MyArrayListTest {
static MyArrayList zoo = new MyArrayList();
public static void printZoo() {
System.out.print("The zoo now holds " + zoo.getArraySize() + " animals: ");
for (int j = 0; j < zoo.getArraySize(); j++) System.out.print(zoo.get(j) + " ");
System.out.println();
}
public static void main(String[] args) {
System.out.println("Testing constructor, add(object) and size() ");
zoo.add("Ant");
zoo.add("Bison");
zoo.add("Camel");
zoo.add("Dog");
zoo.add("Elephant");
zoo.add("Frog");
zoo.add("Giraffe");
zoo.add("Horse");
printZoo();
System.out.println();
}
}
And the Exceptions class
ListFullException.java
public class ListFullException extends RuntimeException{
public ListFullException(String m){
super(m);
}
}
I hope this will be a great study tool for you, if you feel this has helped you, upvote and accept :) :P
It is printing an int because you are calling zoo.get(j) and get() returns ints:
public int get(int i){
for(int index = 0; index< arrays.length; index++) {
}
return i;
You need to return a String, something along the lines of:
public String get(int i){
return arrays[i];
}

Difference in two array deletion code

I have these two code for the deletion of an element from an array ,but there is just one difference the these two for loops for(int k=i;k< l-1;k++)
and for(int k =i;k< l;k++) in first we are de-crementing the size of the length of an array but in second we are not. Both the code are same else and does its deletion job fine. But I couldn't get the difference.
1st
import java.util.Scanner;
public class SearchDeletion1 {
public static void main(String[] args) {
int []a = new int[10];
a[0]=33;
a[1]=11;
a[2]=22;
a[3]=333;
a[4]=343;
a[5]=233;
a[6]=373;
a[7]=3223;
a[8]=313;
a[9]=332;
int i;
System.out.println();
int l=a.length;
Scanner s = new Scanner(System.in);
System.out.println("Enter the item to be searched");
int e = s.nextInt();
//searching
for(i=0;i<l;i++)
if(a[i]==e)
break;
if(i==a.length)
System.out.println("couldn't found");
else
System.out.println("found at position "+"a["+i+"]");
//deleting
for(int k=i;k<l-1;k++)
a[k]=a[k+1];
l--;
System.out.println("item deleted and new array");
for(int q=0;q<l;q++){
System.out.println("a["+q+"]"+"="+a[q]);
}
}
}
2nd
import java.util.Scanner;
public class SearchDeletion2 {
private int a[] ;
SearchDeletion2(int size){
a =new int[size];
}
public void set(int index,int elem){
a[index]=elem;
}
public int get(int index){
return a[index];
}
public static void main(String[] args) {
SearchDeletion2 arr = new SearchDeletion2(100);
arr.set(0,33);
arr.set(1,22);
arr.set(2,11);
arr.set(3,99);
arr.set(4,66);
arr.set(5,44);
arr.set(6,77);
arr.set(7,88);
arr.set(8,55);
arr.set(9,112);
int i;
int l=10;
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
for(i=0;i<l;i++)
if(arr.get(i)==r)
break;
System.out.println(i);
for(int k =i;k<l;k++)
arr.set(k,arr.get(k+1));
l--;
System.out.println(l);
for (int o=0;o<l;o++)
System.out.println(arr.get(o));
}
}
The second piece of code is wrong, because at the last iteration (with k==l-1) it performs arr.get(k+1), which means arr.get(l-1+1), which is arr.get(l), which is an invalid index for an array of l elements (going from 0 to l-1).
The code doesn't break because the actual array is bigger than l (100 'slots' are allocated, against 10 actually used). Anyway, it isn't a code that is safe under all the possible circumstances. So you shouldn't use it.
PS: the code would actually be safe, if the get method was implemented to be somehow resilient to invalid indices. Such as:
public int get(int index){
return (index < size) ? a[index] : 0;
}
You are not increasing or decreasing the size of array at any point in this code. All you are doing is changing the variable l, which dictates how many elements you are going to traverse. So even if you changed the loop to for(int k =i;k<l+10;k++) it would behave in the same way unless you started accessing elements beyond the allocated 100 in which case you would get ArrayIndexOutOfBounds exception.

Comparing one arraylist to another and deleting extra items java

In this method I am trying to compare all the elements in one arraylist to all the elements in another. Then, if an element in the first arraylist does not equal any element in the second arraylist, delete that element. Something is wrong in either the comparison step or the deletion step, but I am not sure which. Any help would be greatly appreciated.
If you want clarification, don't hesitate to ask.
public static ArrayList<Integer> compareArrayandList(ArrayList<Integer>compare, ArrayList<Integer>array2) {
int[] counter = new int[compare.size()];
for (int x: counter) {
x = 0;
}
for (int i = 0; i < compare.size(); i++) {
counter[i] = 0;
for (int number: array2) {
if (compare.get(i) ==number) {
counter[i]++;
}
}
}
for (int i=0; i<counter.length;i++) {
if (counter[i]==0) {
compare.remove(new Integer(i));
}
}
return compare;
}
EDIT: (courtesy of Memento Mori)
The reason your code is not working is that the positions in your ArrayList are changing when you remove an element. Lets say you removed element 3. Now element 3 is different than it was before.
public class Test {
public static ArrayList<Integer> compareArrayandList(ArrayList<Integer>compare, ArrayList<Integer>array2) {
ArrayList<Integer> a3 = new ArrayList<Integer>();
for (Integer a : compare)
{
if(array2.contains(a))
a3.add(a);
}
System.out.println(a3);
return a3;
}
public static void main(String[] args) {
ArrayList<Integer> a1=new ArrayList<Integer>();
ArrayList<Integer> a2=new ArrayList<Integer>();
a1.add(1);
a1.add(5);
a1.add(3);
a2.add(3);
a2.add(4);
a2.add(5);
a2.add(6);
Test test=new Test();
test.compareArrayandList(a1,a2);
}
}
You are not doing what you really want to do here. You remove the element(s) which its value is i from the compare array instead of the element at position i which is not find in the second for loop.
for (int i=0; i<counter.length;i++) {
if (counter[i]==0) {
//compare.remove(new Integer(i)); // problem is here!
// remove element at index i not element equals to i
compare.remove(i);
}
}
You don't need your counter array. You can do the comparison in one step if you use an iterator. I believe this should work:
public static ArrayList<Integer> compareArrayandList(ArrayList<Integer>compare, ArrayList<Integer>array2) {
ListIterator<Integer> iter = compare.listIterator(compare.size());
while (iter.hasPrevious()){
Integer a = new Integer(iter.previous());
for (int number: array2) {
if (a==number) iter.remove();
}
}
return compare;
}
EDIT: The reason your code is not working is that the positions in your ArrayList are changing when you remove an element. Lets say you removed element 3. Now element 3 is different than it was before.
ListUtils.sum(Arrays.asList(firstarray),Arrays.asList(secondarray))

Categories