So I'm trying to figure out to modify this integer sorting algorithm to work with data elements (file names) alphabetically in a listbox but have no idea how?
I understand how the sorting algorithm below works and can implement it using an integer array. However, for listBoxes I can't seem to find any relevant examples on the net.
public partial class MainWindow : Window
{
Random rand = new Random();
int numOfIntegers = 1000;
int[] array;
public MainWindow()
{
InitializeComponent();
array = new int[numOfIntegers];
}
// sort a vector of type int using exchange sort
public void ExchangeSort(int[] array)
{
int pass, i, n = array.Length;
int temp;
// make n-1 passes through the data
for (pass = 0; pass < n - 1; pass++)
{
// locate least of array[pass] ... array[n - 1]
// at array[pass]
for (i = pass + 1; i < n; i++)
{
if (array[i] < array[pass])
{
temp = array[pass];
array[pass] = array[i];
array[i] = temp;
}
}
}
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
ExchangeSort(array);
listBox.Items.Clear();
foreach (int i in array)
{
listBox.Items.Add(i);
}
MessageBox.Show("Done");
}
You could try LINQ:
If I understand correctly, you're trying to sort strings. To compare strings you could simply use the
String.CompareTo()
method or if you need more than simple comparison, theStringComparator
class should do for most use cases.If you choose to do it this way, the condition while sorting would be something like this:
And the rest of the code would probably stay about the same, except of course changing the
int[]
toString[]
.Now, that being said, I would suggest using a
List<String>
and just skip doing this work by hand altogether. SeeList.Sort()
for reference.To be a bit more specific, here's an example based on your code of what I mean.