Merge sorting an array - java

hi i have an array of 9 elements
10 , 5 , 2 , 4 , 6 , 1 , 3 , 2 , 6
i have to sort this using merge sort algorithm . My question is that 6 is been used twice so how will it affect the sorting.

To understand how this would be sorted lets have a look at how the merge sort algorithm really works.
split each element into partitions of size 1
recursively merge adjancent partitions
for i = leftPartStartIndex to rightPartLastIndex inclusive
if leftPartHeadValue <= rightPartHeadValue
copy leftPartHeadValue
else: copy rightPartHeadValue
copy elements back to original array
So lets take the given array [10 , 5 , 2 , 4 , 6 , 1 , 3 , 2 , 6] Here's how the algorithm really runs
Initially split the array into partitions of size 1. So each value in the array is individual partition.
Now merge 10 in position 0 and 5 in position 1 together into 1 partition.
Since 10 > 5, Copy the 5 into a new temporary array of size 2, now the right partition is empty and hence copy 10 into it, so you now have a temporary array which is [5,10] Then copy it back into the original array in the positions making it
[5,10,2,4,6,1,3,2,6]
Now merge the partitions [5,10] to [2] in the 2nd index. Since 5 > 2, copy 2 to the temporary array. Since the right partition is empty copy 5 to the temporary array to the right and similar with 10 thus making [2,5,10]. Now copy the items back to the original array.
[2,5,10,4,6,1,3,2,6]
Now merge the partitions [4,6] and since 4 < 6, copy 4 to the left partition and 6 to the right partition of a temporary array and copy them back to the original array. In this case, the array is unchanged and still looks the same.
[2,5,10,4,6,1,3,2,6].
Now merge partitions [2,5,10] to [4,6], Since 2 < 4, copy 2 to the temporary array, then since 4 < 5, copy 4 to the array, then since 5 < 6 copy 5 and so on until we have a new partition temporary array [2,4,5,6,10] and then copy the elements to the original array [2,4,5,6,10,1,3,2,6]
Now merge the items [1,3] and similarly with [2,6] since value on left side of the partition is lower than that on the right. Then merge [1,3] to [2,6]. Since 1 < 2, copy 1 to temporary array and then 2 and so on to get the new partition [1,2,3,6] and copy it back to the original array making it [2,4,5,6,10,1,2,3,6].
Finally we have 2 partitions to merge i.e. [2,4,5,6,10] and [1,2,3,6]. Repeat the similar process, since 1 < 2, copy 1 to the temporary array and then 2 (because 2 in left partition <= 2 in right partition) so the value 2 from the left partition gets copied to the temporary array. Then 4 is compared to 2 and the value 2 from the right partition is copied to the new temporary array. Then 4 > 3, so 3 is copied and then the 4 < 6 makes 4 be copied and then 5 < 6 (right partition) makes 5 be copied to the temporary array. When we encounter 6 (left partition) to 6 (right partition) and following the condition 6 <= 6 the value 6 from the left partition gets copied to the temporary array. Then the 6 in the right partition is compared to 10 and 6 < 10 so, 6 gets copied to temporary array and then 10. Then the entire temporary array is copied to the original array thus making us obtain the final array. [1,2,2,3,4,5,6,6,10]

Related

Suitable data structure for Java 1000*1000 matrix.

I am practising java programming. I encountered a problem which requires 1000 x 1000 matrix which stores integers value less than 1500
I would want to navigate across all the elements
I might need to fetch max element and its 4 adjacent elements.
What is the best data structure which doesn't affect performance?
1 2 3 4
5 6 7 8
9 10 11 12
12 14 15 16
for the element 11 --> 7, 10, 12, 15 are adjacent elements.
what is wrong with the 2d array data structure?
to get an adjecent of a number at i,j return [i-1][j],[i+1][j],[i][j+1],i[j-1] (you will have to deal with cases where i is zero etc)...
as performance goes, its O(1), doesn't get any better than that...
If you are talking about finding the location of the element. if the matrix is sorted you can simply do a binary search.
A 2dim Array of shorts:
-> short [][] matrix = new short[1000][1000];
| Added variable matrix of type short[][] with initial value [[S#1794d431
Generate in a second, few MB in size. What could be better than that?

How to find Path of Lowest Cost in 2D matrix

i have a Challenge the objective is to get the lowest cost of the path.
The path can proceed horizontally or diagonally. not vertically. like below.
and the first and last row are also adjacent.
for example see below matrix:
output for 1st matrix :
16
1 2 3 4 4 5-->path row number
output for second matrix:
11
1 2 1 5 4 5-->path row number
am doing it in java, am getting the Lowest path but am not getting the path to print the path using row numbers.
int minCost(int cost[r][r], int m, int n)
{
if (n < 0 || m < 0)
return Integer.MAX_VALUE;;
else if ((m == r-1 && n == c-1)|| n+1>=c)
return cost[m][n];
else
return cost[m][n] + min( minCost(cost, m+1>=r?r-1:m+1,n+1),
minCost(cost, m,n+1),
minCost(cost, m-1>=0?m-1:r-1,n+1));
}
// calling it
minCost(cost, 0, 0);
How to get the row numbers for shortest path?
Your algorithm is quite inefficient. The best solution I can think is calculating it backwards(from right to left). Consider the right 2 columns of your second matrix:
8 6
7 4
9 5
2 6
2 3
If now we are on the cell with value 8, the next step can be 6/4/3. Of course we choose 3 because we want a smaller cost. If now we are on the cell with value 7, the next step can be 6/4/5, we will choose 4. So the two columns can merged into one column:
11 //8+3
11 //7+4
13 //9+4
5 //2+3
5 //2+3
Now repeat the last two columns:
2 11
2 11
9 13
3 5
1 5
Finally the matrix will be merged into one column, the smallest value in the column has the lowest cost.
I'll try to expand on fabian's comment:
It's clear that your minCost function will return the same values if called with the same arguments. In your algorithm, it indeed does get called lots of times with the same values. Every call for column zero will generate 3 calls for column 1, which in turn generate 9 calls for column 2, etc. The last column will get a huge number of calls (3^r as fabian pointed), most of them recalculating the very same values for other calls.
The idea is to store these values so they don't need to be recalculated every time they are needed. A very simple way of doing this is to create a new matrix of the same size as the original and calculating, column by column, the minimum sum for getting to each cell. The first column will be trivial (just copy from the original array, as there is only one step involved), and then proceed for the other columns reusing the values already calculated.
After that, you can optimize space usage by replacing the second matrix by only two columns, as you are not going to need column n-1 once you have column n fully calculated. This can be a bit tricky, so if you're unsure I recommend using the full array the first time.

creating set from input

I want to create a set of elements from the given input.
(i.e. i/p : 5 5 4 4 4 3 3 3 3 2 2 2 1 1 1 ,then o/p : 5 4 3 2 1)
I have a logic: create an array and store the elements in it.successively read elements and write a loop which will assign boolean false if two elements (the current chosen element and an element from the array whose index is less than that of the current element) are not the same. After the loop has executed for an element , all the boolean values stored are passed through bitwise OR operation and if the overall value is false , then the current element is pushed to an array that stores the set and the next element is the given sequence is chosen and same operation is performed.
I haven't yet written the code for this. So, is this algo. right? Also, do you know a better algo. to find a set?
Thanks.
You never need to use arrays for this sort of thing. Learn about Lists and Sets and use those instead.
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(5, 5, 4, 4, 3, 2, 4, 3, 1));
System.out.println(set); // prints [5, 4, 3, 2, 1]

Quicksort tree diagram with "middle" pivot?

This is in java. Suppose that your Quick-Sort algorithm uses a pivot rule that picks the element in the “middle”. That is, for an array A[0,1,...,n−1] of size n, it uses the element in A[n/2] as pivot if n is even and the element in A[(n − 1)/2] as pivot if n is odd. Illustrate how this algorithm works using a quick-sort tree on the input:
[7 6 5 4 3 2 1]
Would the first pivot be 5 or 4? I was thinking it would be 5 since (7-1)/2 = 3 and 5 is the 3rd element, or would it be the 3rd index, which is the element 4?
size of your array is 7
the size is odd so [(n-1)/2] will be used -> [(n-1)/2] = [(7-1)/2] = 3
It will be 3rd index i.e. 4th element
which is in your case 4
[7 6 5 4 3 2 1] has 7 elements, so being odd you said it calculates the pivot using: A[(n-1)/2]
So, (7-1)/2 => 6/2 => 3rd position in the array, in your case number 4
Take into account that this kind of division will always return a truncated integer.
For example, 5/2 = 2, 3/2 = 1

how to delete an element in a two dimensional array in java?

let the array be
5 1 6 8
2 4 9 3
1 9 3 2
5 3 8 9
in the above shown array i need to delete the last element of even rows (2,4rows). So that my new array looks like
5 1 6 8
2 4 9 1
9 3 2 5
3 8
Please help how to do this with java code?
It looks like you are trying to treat this 2d array as a single array which is just being displayed in 2d. Maybe you should just use a single ArrayList and remove the elements normally.
Maybe you have to use a internal ArrayList (Single dimension) and have
a method that returns an
bidimensional array
a methos that removes the x position in line y
Your class must have the dimension size (maybe in the constructor).
You should assign the last element of your 2D array to be a new 1D array containing only the elements you want to keep:
arr[3] = new int[] {arr[3][1], arr[3][3]};
(assuming your array arr is of type int[][])
Treat it as a list and iterate backward and delete all items divisible by 8 and you will get the result you are hoping to get , and in case you want in array format , you can convert the its to array or 2D array

Categories

Resources