Okay, I know this question doesn't show research effort, but I've been going through this code so many times and I couldn't figure out was I was doing wrong. I know there are many Mergesort implementation examples but I wanted to do it my way. Any help is appreciated, thanks.
import java.util.Scanner;
public class MergeSort
{
public static int[] mergeSort(int[] arr)
{
if (arr.length > 1)
{
int[] arr1 = splitLeft(arr);
int[] arr2 = splitRight(arr);
arr1 = mergeSort(arr1);
arr2 = mergeSort(arr2);
return merge(arr1, arr2);
}
else
return arr;
}
public static int[] splitLeft(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[middle];
for (int i = 0; i < middle; i++)
newarr[i] = arr[i];
return newarr;
}
public static int[] splitRight(int[] arr)
{
int middle = arr.length / 2;
int[] newarr = new int[arr.length - middle];
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
return newarr;
}
public static int[] merge(int[] arr1, int[] arr2)
{
int[] sorted = new int[arr1.length+arr2.length];
int i1 = 0;
int i2 = 0;
int i = 0;
while (i1 < arr1.length && i2 < arr2.length)
{
if (arr1[i1] < arr2[i2])
{
sorted[i] = arr1[i1];
i1++;
}
else
{
sorted[i] = arr2[i2];
i2++;
}
i++;
}
while (i1 < arr1.length)
{
sorted[i] = arr1[i1];
i1++;
i++;
}
while (i2 < arr2.length)
{
sorted[i] = arr1[i2];
i2++;
i++;
}
return sorted;
}
public static int getNum(int x)
{
int num = (int)(Math.random()*x + 1);
return num;
}
public static void printArr(int[] arr)
{
System.out.println();
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
static Scanner reader = new Scanner(System.in);
public static void main(String [ ] args)
{
int i;
System.out.println("Type the length of the array");
int n = reader.nextInt();
System.out.println("Type the range of the random numbers generator");
int range = reader.nextInt();
int[]arr = new int[n];
for (i = 0; i < n; i++)
arr[i] = getNum(range);
printArr(arr);
int[] sorted = new int[n];
sorted = mergeSort(arr);
printArr(sorted);
}
}
I think the problem is in your splitRight function. Consider this code:
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
This tries to copy the ith element from arr to the ith position of newarr, but this is incorrect. For example, if the array arr has ten elements, you want to copy element 5 of arr to position 0 of newArr, element 6 of arr to position 1 of newarr, etc.
To fix this, consider trying something like this:
for (int i = 0; i + middle < arr.length; i++)
newarr[i] = arr[i + middle];
Hope this helps!
When you do
for (int i = middle; i < arr.length; i++)
newarr[i] = arr[i];
You are surely asking for positions in the original array and at the same time looking for them in the new array (which happens to be shorter).
Related
My program isn't sorting the numbers at all. It displays them in the order they were initially entered. It must sort them from smallest to largest number. The code below should find the largest number in the array and swap it with the last .the code is below:
import java.util.Scanner;
public class maxSorttt {
public static void main(String[] args) {
double[] ten = new double[10];
Scanner input = new Scanner(System.in);
System.out.print("Enter 10 numbers: ");
for (int i = 0; i < ten.length; i++)
ten[i] = input.nextDouble();
sort(ten);
}
public static void sort(double[] array) {
for (int i = array.length - 1; i < 0; i--) {
double currentMax = array[i];
int currentMaxIndex = i;
for (int x = i - 1; x < -1; x--) {
if (currentMax < array[x]) {
currentMax = array[x];
currentMaxIndex = x;
}
}
if (currentMaxIndex != i) {
array[currentMaxIndex] = array[i];
array[i] = currentMax;
}
}
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
}
}
I believe your problem is here:
for(int i=array.length-1; i<0; i--)
array.length is not less than 0 so the for loop never runs. You probably wanted
for(int i=array.length-1; i>=0; i--)
Be Simple!
public static void selectionSort(double[] arr) {
for (int i = 0; i + 1 < arr.length; i++) {
int minIndex = findMinIndex(arr, i + 1);
if (Double.compare(arr[i], arr[minIndex]) > 0)
swap(arr, i, minIndex);
}
}
private static int findMinIndex(double[] arr, int i) {
int minIndex = i;
for (; i < arr.length; i++)
if (Double.compare(arr[i], arr[minIndex]) < 0)
minIndex = i;
return minIndex;
}
private static void swap(double[] arr, int i, int j) {
double tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
I have this professor that wants us to make a using the method header
Public static int[] eliminateDuplicates(int[] arr)
The program uses a randomly generated array to see if there are duplications but the user gives a limit on how many indexes's the random array has. Here is what I have but it's not working.
import java.util.Random;
import java.util.Scanner;
public class Dublicates
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
System.out.println("Enter array length: ");
int[] a = new int[input.nextInt()];
for (int i = 0; i<a.length; i++)
{
a[i] = generator.nextInt(a.length*2);
}
int[] result = eliminateDuplicates(a);
System.out.println("The new numbers are: " + result.length);
System.out.println("The double numbers were:");
for (int b : result)
{
System.out.println(b + " ");
}
}
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = temp[i];
}
{
return result;
}
}
}
public static int linearSearch(int[] arr, int key)
{
for(int i = 0; i<arr.length; i++)
{
if (key == arr[i])
return i;
}
return -1;
}
}
As your statements making the final result is inside the for loop, the statements inside for will only run once and will not give the right answer.
So you have to change your code as follows.
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
}
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = temp[i];
}
return result;
}
The default values in the integer array is 0, The Random.nextInt() can generate 0 random value, When you run linear search then 0 will not be included in the final resultant array.
I have modify Random.nextInt() so that it will not generate 0 random number:
import java.util.Random;
import java.util.Scanner;
public class HelloCodiva
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Random generator = new Random();
System.out.println("Enter array length: ");
int[] a = new int[input.nextInt()];
for (int i = 0; i<a.length; i++){
a[i] = generator.nextInt(a.length*2)+1;//So that 0 is not generated
}
int[] result = eliminateDuplicates(a);
for (int originalValue: a){
System.out.println(originalValue+ " ");
}
System.out.println("The new numbers are: " + result.length);
System.out.println("The double numbers were:");
for (int b : result){
System.out.println(b + " ");
}
}
public static int[] eliminateDuplicates(int[] arr)
{
int[] temp = new int[arr.length];
int size = 0;
for (int i = 0; i < arr.length; i++) {
if (linearSearch(temp, arr[i]) == -1) {
temp[size] = arr[i];
size++;
}
}
int[] result = new int[size];
System.arraycopy(temp, 0, result, 0, size);
return result;
}
public static int linearSearch(int[] arr, int key)
{
for(int i = 0; i<arr.length; i++)
{
if (key == arr[i])
return i;
}
return -1;
}
}
I am stuck with an exercise which tells me to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
But it is throwing out three exact same numbers.
You don't need a nested for loop - just iterate over the source array and fill the result array in the opposite order:
public int[] reverse(int[] nums) {
int len = nums.length;
int[] result = new int[len];
for (int i = 0; i < len; ++i) {
result[len - i - 1] = nums[i];
}
}
From a first look, your code should be more like this:
public int[] reverse3(int[] nums)
{
// initialize a second array with the same length
int[] nums2 = new int[nums.length];
// initialize the nums2 index
int index = 0;
// you only need one loop for this (since we'll be incrementing the index of nums2)
for (int i = nums.length - 1; i >= 0; i--) {
nums2[index] = nums[i];
index++;
}
return nums2;
}
Swap the symetric values in the array like this :
public static void reverse(int[] nums) {
for (int i = 0; i < nums.length / 2; i++) {
int temp = nums[i];
nums[i] = nums[nums.length - 1 - i];
nums[nums.length - 1 - i] = temp;
}
To reverse an array you only have to swap the elements until the midpoint:
public int[] reverse(int[] nums) {
int numsLength = nums.length;
for (int i = 0; i < numsLength / 2; i++) {
int temp = nums[i];
nums[i] = nums[numsLength - i - 1];
nums[numsLength - i - 1] = temp;
}
return nums;
}
This way is much more optimized.
Source: How do I reverse an int array in Java?
I am new to Java development and sorry if this question will be too
silly, but it seems like I am stuck with the exercise which tells me
to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
} } return nums2; }
But it is throwing out three exact same numbers. Could I please count
on some help? Thank you
Use one loop only. If you want to use 2 arrays(wich i do not see the point.) this will work:
int j = 0;
for(int i = nums.length -1; i >= 0; i--){
nums2[j] = nums[i];
j++;
}
But if you want to use only one array, you can do this:
for (int i = 0; i < nums.length/2; i++) {
int aux = nums[i];
nums[i] = nums[nums.length-i-1];
nums[nums.length-i-1] = aux;
}
There are so many efficient ways to do it but to make you understand i am gonna modify your own code
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = (nums.length-1) - i; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
or let's do a a little bit modification rather than using nums.length() again and again we can put it inside a variable
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
int length = nums.length;
for (int i = length - 1; i >= 0; i--) {
for (int j = (length-1) - i; j < length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
Remember it is not an efficient way but to make you understand i just modify the logic. Using nested loops like that will decrease the performance so better avoid it and try to do it in much more optimized way..
Here is my code for a mergesort in java:
public class MergeSort {
public static void mergesort(int[] input) {
int inputSize = input.length;
if(inputSize < 2) {
return;
}
int[] left = new int[inputSize/2];
int[] right = new int[inputSize/2];
int count = 0;
for(int i=0; i < inputSize/2; i++) {
left[i] = input[i];
}
for(int i=inputSize/2; i<inputSize; i++) {
right[count] = input[i];
count++;
}
mergesort(left);
mergesort(right);
merge(left, right, input);
}
public static int[] merge(int[] returnArr, int[] left, int[] right) {
int leftSize = left.length;
int rightSize = right.length;
int i = 0;
int j =0;
int k = 0;
int count = 0;
while(i < leftSize && j < rightSize) {
if(left[i] <= right[j]) {
returnArr[k] = left[i];
i++;
}
else {
returnArr[k] = right[j];
j++;
}
k++;
}
while(i<leftSize) {
returnArr[k] = left[i];
i++;
k++;
}
while(j < rightSize) {
returnArr[k] = right[j];
j++;
k++;
}
for(int x=0; x<returnArr.length; x++) {
System.out.print(returnArr[x]);
}
return returnArr;
}
public static void main(String[] args) {
int[] array = {3,4,6,2,7,1,8,6};
mergesort(array);
}
}
My issue is that I'm getting an out of bounds exception.
I'm using the debugger and have found that after mergesort(left) and mergesort(right) have finished recursively running.
The arrays left and right, which go into the merge function, have the values [3] and [4] respectively, which is correct.
But when the debugger jumps into the merge function, left has value [3] and right, for some reason is length 2 and has the value [3,4].
This is the source of my out of bounds exception, though I'm not sure why when the merge function runs for its first time, it changes the value of "right".
One problem that is readily visible is that the you shouldn't make 2 arrays of size inputSize/2. Make two arrays of inputSize/2 and inputsize-inputSize/2. Otherwise the algorithm would fail for odd length array.
Also call the function with proper order of the arguments. merge( input, left, right);
I fixed your code and merged them to 1 method, left.length and right.length are limited by input.length so you only need to loop by input.length:
public static void mergeSort(int[] input)
{
if (input.length < 2)
{
return;
}
int[] left = new int[input.length / 2];
int[] right = new int[input.length - input.length / 2];
for (int i = 0; i < input.length; i++)
{
if (i < input.length / 2)
left[i] = input[i];
else
right[i - input.length / 2] = input[i];
}
mergeSort(left);
mergeSort(right);
for (int i = 0, l = 0, r = 0; i < input.length; i++)
{
if (l >= left.length)
{
input[i] = right[r];
r++;
}
else if (r >= right.length)
{
input[i] = left[l];
l++;
}
else
{
if (left[l] >= right[r])
{
input[i] = right[r];
r++;
}
else
{
input[i] = left[l];
l++;
}
}
}
}
you had two problems with your code:
1- as #coderredoc said: your left and right array sizes are wrong:
exemple: if you had an array of 7 elements, your left and right arrays would have a size of 7/2 = 3 so you would have a total of 6 elements in left and right arrays and not 7.
2- you are calling merge function in the mergeSort function with wrong parameters order:
it should be returnArr, left, right and not left,right, returnArr.
Explanation:
if you pass the left array as the first parameter, it would merge the right and the returnArr in the left array. But your left array has a size of 3 and the sum of the sizes of the others is 7 + 3 = 10 that's why you got an OutOfBoundsException.
you need to call merge(input,left,right);
here is the final version:
public class MergeSort {
public static void mergesort(int[] input) {
int inputSize = input.length;
if(inputSize < 2) {
return;
}
int[] left = new int[inputSize/2];
int[] right = new int[inputSize-inputSize/2];
int count = 0;
for(int i=0; i < inputSize/2; i++) {
left[i] = input[i];
}
for(int i=inputSize/2; i<inputSize; i++) {
right[count] = input[i];
count++;
}
mergesort(left);
mergesort(right);
merge(input,left, right);
}
public static int[] merge(int[] returnArr, int[] left, int[] right) {
int leftSize = left.length;
int rightSize = right.length;
int i = 0;
int j =0;
int k = 0;
int count = 0;
while(i < leftSize && j < rightSize) {
if(left[i] <= right[j]) {
returnArr[k] = left[i];
i++;
}
else {
returnArr[k] = right[j];
j++;
}
k++;
}
while(i<leftSize) {
returnArr[k] = left[i];
i++;
k++;
}
while(j < rightSize) {
returnArr[k] = right[j];
j++;
k++;
}
for(int x=0; x<returnArr.length; x++) {
System.out.print(returnArr[x]);
}
return returnArr;
}
public static void main(String[] args) {
int[] array = {3,4,6,2,7,1,8,6};
mergesort(array);
}
}
I am trying to merge to arrays of int type with the same size. Here's my code
public class classA
{
static int[] mergeArray(int[] arr1, int arr2[])
{
int arr3[] = new int[arr1.length+ arr2.length];
int count = 0;
for(int i = 0; i < arr1.length; i++){
arr3[count] = arr1[i];
count++;
arr3[count] = arr2[i];
}
for(int i = 0; i < arr3.length; i++){
System.out.print(arr3[i]);
}
return arr3;
}
public static void main(String[] args) throws IOException
{
int arr1[] = {1,2,3};
int arr2[] = {4,5,6};
int arr3[] = mergeArray(arr1,arr2);
}
}
When I try printing the numbers in first for loop, it gives me 1,4,2,5,3,6 which the correct output. But, When I try printing it outside the first for loop it gives me output 1,2,3,6,0,0. Can someone help me?
TIA
In your for loop, when you copy from arr2 you need to increment your count.
arr3[count] = arr2[i];
count++;
You could also simplify your code a bit like,
static int[] mergeArray(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length * 2];
int count = 0;
for (int i = 0; i < arr1.length; i++) {
arr3[count++] = arr1[i];
arr3[count++] = arr2[i];
}
return arr3;
}
And print in main like
int arr3[] = mergeArray(arr1, arr2);
System.out.println(Arrays.toString(arr3));
or in Java 8+, use a flatMap and IntStream like
static int[] mergeArray(int[] arr1, int[] arr2) {
return IntStream.range(0, arr1.length)
.flatMap(i -> IntStream.of(arr1[i], arr2[i])).toArray();
}
for the same result.
Following your code, you forget to upgrade the count after appending the second value:
public class classA
{
static int[] mergeArray(int[] arr1, int arr2[])
{
int arr3[] = new int[arr1.length+ arr2.length];
int count = 0;
for(int i = 0; i < arr1.length; i++){
arr3[count] = arr1[i];
count++;
arr3[count] = arr2[i];
count++; //////////////// here!
}
for(int i = 0; i < arr3.length; i++){
System.out.print(arr3[i]);
}
return arr3;
}
public static void main(String[] args) throws IOException
{
int arr1[] = {1,2,3};
int arr2[] = {4,5,6};
int arr3[] = mergeArray(arr1,arr2);
}
}
explain:
in you code you do count++; just once in the foor loop, but, the foor loop goes from 0 to arr1.length, the is equal to arr3.length/2, it means you forget the half of the values, that's why the 0's appear here, because when you start a new array the defaul value in int[] are 0.
Use arr3[count+1] = arr2[i] and count += 2 instead.
It could be easily understood than using count++ twice.
static int[] mergeArray(int[] arr1, int arr2[])
{
int arr3[] = new int[arr1.length+ arr2.length];
int count = 0;
for(int i = 0; i < arr1.length; i++){
arr3[count] = arr1[i];
arr3[count+1] = arr2[i]; ///////here
count+=2; ///////and here
}
for(int i = 0; i < arr3.length; i++){
System.out.print(arr3[i]);
}
return arr3;
}
You simply need to add two values and then increase the kth value.
static int[] array1 = { 1, 2, 3, 4,9 };
static int[] array2 = { 5, 6, 7, 8 };
private static void mergeArrays(int[] arr1, int[] arr2) {
int[] arr3 = new int[arr1.length + arr2.length];
int k = 0;
for (int i = 0,j=0; i < arr1.length && j < arr2.length; i++,j++) {
arr3[k] = arr1[i];
arr3[++k] = arr2[j];
k++;
}
for (int i = 0; i < arr3.length; i++) {
System.out.println("arr3: " + arr3[i]);
}
}