Quicksort tree diagram with "middle" pivot? - java

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

Related

Merge sorting an array

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]

How to find optimal line on y axis using a divide and conquer algorithm?

If I am given a group of numbers that are positions on the y axis how do I find the position on the y axis that is has the shortest total difference in respect to the group of numbers. For example, if you are give the numbers 1 8 3 6 2 7 it should return the number 5 because it has the smallest total difference at 15. It has to be a divide and conquer approach. I do not need code I need an explanation.
Let's take your example: 1 8 3 6 2 7. I'm assuming we're looking for an integer answer.
The answer has to be between the smallest and the largest number. 0 has a larger sum of differences than 1. 8 has a smaller sum of differences than 9.
With your example, the end bounds are 1 and 8. Add them together and integer divide by 2. This gives us 4. Or, as an alternative, add all the numbers together and divide by the number count. With your example the sum is 27. Integer dividing by 6 yields 4.
The sum of the differences for 4 is 15. First, let's back up and see if the answer is smaller.
The sum of the differences for 3 is 15. So, let's back up again.
The sum of the differences for 2 is 17. We don't have to go any further in this direction. So, going the other direction from 4.
The sum of the differences for 5 is 15. So, let's move forward.
The sum of the differences for 6 is 15. Again, let's move forward.
The sum of the differences for 7 is 17.
So, the final answer is 3, 4, 5, or 6. I'm not sure how you choose one to be the correct answer.
In this case, we could have just checked all the numbers between 1 and 8, inclusive. But when the integers get to be larger, like 1,000, this divide and conquer method is faster.
Sort the numbers. You can use a divide and conquer algorithm for that.
Then the optimal line is at the number in the middle, or anywhere between the two middle numbers if there are an even number of them.
Notice that in your example, 3, 4, 5, and 6 all have a total difference of 15.
Why this works:
If you have n numbers above your line and m numbers below your line, and you move your line by 'x', then the change in the total difference is m*x - n*x. So if your line has more numbers above, then you should move it up. If it has more numbers below, then you should move it down. When it has the same number above and below, then it's optimal.

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.

Sorting - Is it ever possible to sort using subarrays well?

I came across an array sorting algorithm that seems pretty good, however it recurses using sub-arrays. I heard the time complexity of making a sub-array is O(n), which more or less stops any efficient sort from using sub-arrays.
The algorithm:
Take a pivot. We'll call it the last number in the array every time for the purpose of demonstration.
Put the pivot in its correct place. Here, you would look at 2 and 6, and if 6 is greater, put it after 2. Then look at 1 and 2, and if it's less, put it on the left. If two numbers are equal, I chose to put the pivot on the left.
Take the sub-arrays on both the left and right side of the pivot and recur on those.
Stop when the sub-array size is one.
A worked example:
6 1 7 8 6 9 1 2 Pivot would be 2
1 1 2 6 6 7 8 9 Put 2 in it's place, time to take sub-arrays
[1 1] 2 [6 7 8 9] Recur.
1 1 2 [6 7 8] 9 Recur more.
1 1 2 [6 7] 8 9 Recur.
1 1 2 6 7 8 9 Done!
What is the time complexity? Also, I'd be interested to see the time complexity if taking a subarray just takes O(1) time.
I think worst case this algorithm is O(n^2), but what is it average case?
Also please don't link a better sort, I'm trying to figure out a good sort on my own.
You have described the Quick Sort algorithm, which has average time complexity of O(n log n) and worst case time complexity of O(n^2) (oddly enough when the array is already sorted).

General: Search time in algorithm

i have a general question (taken from some computer science test) i'd like to get an explanation for, the question was:
Sorted array given a particular size, and suppose we use the fastest method in computer science to find values ​​in the array. In this method, the search time of any element is no more than N seconds. Now we multiply the size of the array. The search time of any element in the array will be at most:
Answer: N+1.
Can anyone please give me a full explanation why this is the answer? and why isn't it 2*N ?
Thanks.
I think that the sentence "In this method, the search time of any element is no more than N seconds" is there just to confuse you.
I will ignore the seconds and consider it as O(N) steps.
There is an algorithm to find the element in log(x) steps (binary search - see the other answe). So
log2(x) = N
log2(2*x) = N+1
(I know this is not very precise and formal, but I hope you get the idea).
I suppose they mean binary search algorithm as fastest method for searching in sorted array. It is algorithm of type "divide and conquer", so for one step of such algorithm we reduce searching area by half.
Example:
Let's define one step in our algorithm take 1 unit of time
array = [1 2 3 4 5 6 7 8], to find = 7
We test our value as the last element in first array.
1 step: divide into [1 2 3 4] and [5 6 7 8], 4 < 7, our value in second array
2 step: divide into [5 6] and [7 8], 6 < 7, our value in second array
3 step: divide into [7] and [8], 7 = 7, we found it.
It is how binary search works and consumes 3 units of time.
Now imagine we doubled array to [1..16], we need 1 more step to reduce array to previous one, so we need 4 units of time.

Categories

Resources