The code below is an example of a sort but their is a bug in the program that I
ID: 3698913 • Letter: T
Question
The code below is an example of a sort but their is a bug in the program that I can not figure out. If you could explain why you added or changed a section to sort the array, it'll be greatly appreicated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bi_direactional4_HW
{
class Program
{
static void Main(string[] args)
{
int[] x = { 26, 86, 2, 65, 83, 1 };
Sort(ref x);
for (int i = 0; i <= x.Length - 1; i++)
{
Console.Write(x[i] + " ");
}
Console.ReadLine();
}
public static void Sort(ref int[] x)
{
int i, j, temp;
int increment = 3;
while (increment < 0)
{
for ( i = 0; i < x.Length; i++)
{
j = 1;
temp = x[i];
while ((j >= increment) && (x[j - increment] > temp))
{
x[j] = x[j - increment];
j = j - increment;
}
x[j] = temp;
}
if (increment / 2 != 0)
{
increment = increment / 2;
}
else if (increment == 1)
{
increment = 0;
}
else
{
increment = 1;
}
}
}
}
}
Explanation / Answer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Bi_direactional4_HW
{
class Program
{
static void Main(string[] args)
{
int[] x = { 26, 86, 2, 65, 83, 1 };
Sort(ref x);
for (int i = 0; i <= x.Length - 1; i++)
{
Console.Write(x[i] + " ");
}
Console.ReadLine();
}
public static void Sort(ref int[] x)
{
int n = x.Length;
int temp;
for (int i = 0; i < n; i++) {
int j = 1;
while (j < (n - i)) {
if (x[j - 1] > x[j]) {
// swap the elements!
temp = x[j - 1];
x[j - 1] = x[j];
x[j] = temp;
}
j++;
}
}
}
}
}
Output: