Monday, November 24, 2008

Sorting Array of Strings Alphabetically without using inbuilt dotnet methods

//Main function to print sorted array
static void Main(string[] args)
{
Program pr = new Program();

//Array of element.
string[] array = { "nitendra","abhijit","nsr","manish","rahul","zaheer","abhishek","msdfDS","xyz","123"};
pr.sort(array);
for (int i = 0; i <= array.Length-1 ; i++)
{
Console.WriteLine(array[i]);
}
}

//Function to compare two strings

public int Compare(string str1, String str2)
{
int len1, len2, i;
len1 = str1.Length;
len2 = str1.Length;
for (i = 0; i < len1 && i < len2; i++)
{
if (str1[i] < str2[i])
return -1;
else if (str1[i] > str2[i])
return 1;
}
return 0;
}

//Function to sort array of strings

public void sort(String[] array)
{
int i, j;
String temp;
int sortTheStrings = array.Length-1;
for (i = 0; i < sortTheStrings; ++i)
for (j = 0; j < sortTheStrings; ++j)
if (Compare(array[j],(array[j + 1])) > 0)
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}

No comments: