Write a program in C# to display the list of items in the array according to the length of the string in ascending order and the original order. The array should contain the following data “ROME, LONDON, NAIROBI, CALIFORNIA, ZURICH, NEW DELHI, AMSTERDAM, HOUSTON, PARIS". The output should be as follow
Here is the arranged list:
ROME
PARIS
LONDON
ZURICH
HOUSTON
NAIROBI
AMSTERDAM
NEW DELHI
CALIFORNIA
Here is the original list
ROME
LONDON
NAIROBI
CALIFORNIA
ZURICH
NEW DELHI
AMSTERDAM
HOUSTON
PARIS
If you have any doubts, please give me comment...
using System;
class Excercise {
public static void Main () {
string[] items = { "ROME", "LONDON", "NAIROBI", "CALIFORNIA", "ZURICH", "NEW DELHI", "AMSTERDAM", "HOUSTON", "PARIS" };
string[] sortedItems = (string[]) items.Clone ();
for (int i = 0; i < sortedItems.Length; i++) {
for (int j = 0; j < sortedItems.Length-i-1; j++) {
int len1 = sortedItems[j].Length;
int len2 = sortedItems[j+1].Length;
if (len1 > len2 || (len1==len2 && sortedItems[j].CompareTo(sortedItems[j+1])>0)) {
string temp = sortedItems[j];
sortedItems[j] = sortedItems[j+1];
sortedItems[j+1] = temp;
}
}
}
Console.WriteLine ("Here is the arranged list:");
for (int i = 0; i < sortedItems.Length; i++) {
Console.WriteLine (sortedItems[i]);
}
Console.WriteLine ("Here is the original list:");
for (int i = 0; i < items.Length; i++) {
Console.WriteLine (items[i]);
}
}
}
Get Answers For Free
Most questions answered within 1 hours.