private static int partition(int[] array,int links, int rechts)
{
int pivotelement = array[links]; //pivotelement on the left
int i = links; // links means leftside
int j = rechts; // rechts means rightside
while (i <= j)
{
if (array[i] <= pivotelement)
{
i++;
}
else if (array[j] > pivotelement)
{
j--;
}
else
{
swap(array,i,j); **//first swap makes sense to me**
i++;
j--;
}
}
swap(array,links,j); **//Here is the second swap. Im not sure about that but it works**.
return j;
}
public static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Im expecting a explanation of the second swap. Why is it necessary?
I found out that in a sorted list i dont need the second swap. Sorry thats my first Question in Stack Overflow. When you need more Information just ask for it.
These are the arrays i try it with and it works.
int[] array = {1,2,3,4,5,6,7,8,9,10};
int[] array = {4,7,4,6,8,2,3,4,6,2};
int[] array = {8,4,6,3,7,1,0,9,5,22};
int[] array = {1};
>Solution :
The second swap in the partition function is there to place the pivot element in its correct sorted position in the array.
Once the loop in the partition function finishes, it means that i and j have crossed each other, and the elements to the left of j are less than or equal to the pivot, while the elements to the right of j are greater than the pivot.
However, the pivot element is still at array[links]. To place the pivot in its correct sorted position, you need to swap it with the element at index j. After this swap, the pivot element is at its correct position, and all elements to the left of it are smaller or equal, and all elements to the right are greater.