'Title of shakersort
I am currently taking a Data Structure and Algorithm and part of an exercise is to implement the shaker sort algorithm. Instead of separating two for loops, I have included a for-j loop inside a for-i loop. Is that possible?
public static void shakerSort(int array[], int n)
{
boolean swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < n - 1; i++)
{
if (array[i] > array[i + 1])
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
if (i == n - 2)
{
if (!swappped)
{
break;
}
else
{
swapped = false;
for (int j = n - 1; j > 0; j--)
{
if (array[j - 1] > array[j])
{
int temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
swapped = true;
}
}
if (!swapped)
{
break;
}
}
}
}
}
Output:
-5
-3
5
9
11
12
15
18
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
