how to bubble sort an array in c# code example
Example 1: bubble sort c#
using System;
namespace BubbleSort {
class Sorting {
static void Main(string[] args) {
int[] mixdata = { 56, 23, 2, 86, 45, 102 };
int temp;
for (int j = 0; j <= mixdata.Length - 2; j++) {
for (int i = 0; i <= mixdata.Length - 2; i++) {
if (mixdata[i] > mixdata[i + 1]) {
temp= mixdata[i + 1];
mixdata[i + 1] = mixdata[i];
mixdata[i] = temp;
}
}
}
Console.WriteLine("Bubble sort data:");
foreach (int p in mixdata)
Console.Write(p + " ");
Console.Read();
}
}
}
Example 2: c# bubble sort string array
You can use string.Compare(x,y) instead of <, which returns 0 if the string are equal, otherwise an integer that indicates their relative position in the sort order
for (int index = 0; index < (letters.Length - 1); index++)
{
if (string.Compare (letters[index], letters[index + 1]) < 0)
{
temp = letters[index];
letters[index] = letters[index + 1];
letters[index + 1] = temp;
swap = true;
}
}
If you want to ignore case during the comparison, you should use string.Compare (letters[index], letters[index + 1], true)