Сортировка массива - C# (204652)
Формулировка задачи:
Решил отсортировать массив, но выкидывает ошибку Index out of range exception was unhandled и указывает на "i = 0" во втором цикле for. Подскажите как сделать правильно, исходя из этого варианта, другие способы сортировки не интересуют.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int c; int i; int j; int size; size = Convert.ToInt32(Console.ReadLine()); int[] ar = new int[size]; Random r = new Random(); for(j = 0; j < ar.Length; j++) { ar[j] = r.Next(9); Console.WriteLine(ar[j]); } do for (i = 0; i < ar.Length-1;i++) { if (ar[i]>ar[i+1]) { c = ar[i+1]; ar[i+1] = ar[i]; ar [i] = c; } } while (ar[i]<=ar[i+1]); Console.ReadLine(); } } }
Решение задачи: «Сортировка массива»
textual
Листинг программы
class Program { static void Main() { int t, j, size; bool swaps; Console.Write("Введите размерность массива: "); size = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(); int[] ar = new int[size]; Random r = new Random(); for (j = 0; j < ar.Length; j++) ar[j] = r.Next(11); Program.PrintArray(ar); do { swaps = false; for (int i = 0; i < ar.Length - 1; i++) { if (ar[i] > ar[i + 1]) { t = ar[i + 1]; ar[i + 1] = ar[i]; ar[i] = t; swaps = true; } } } while (swaps); Program.PrintArray(ar); Console.Read(); } public static void PrintArray(int[] ar) { for (int i = 0; i < ar.Length; i ++ ) Console.Write("{0,4}", ar[i]); Console.WriteLine(); } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д