F
F
Fayson712019-05-16 23:17:29
Algorithms
Fayson71, 2019-05-16 23:17:29

How to fix the program (shaker sort)?

Help me figure it out, on line 28, where the first for loop of the algorithm itself begins, it gives an error that the index is out of scope of the array:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BubbleSort
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] a = new int[5];
            int i = 0, left = 0, right = 4, last = 5, z;
            Random random = new Random();
            for (i = 0; i < a.Length; i++)
            {
                a[i] = 0 + random.Next(100);
            }
            foreach (int element in a)
                Console.Write(element + " ");
            Console.WriteLine();

            while (left < right)
            {
                for (i = right; i >= left; i--) //здесь ошибка
                {
                    if (a[i - 1] > a[i])
                    {
                        z = a[i - 1];
                        a[i] = a[i - 1];
                        a[i - 1] = z;
                        last = i;
                    }
                }
                left = last + 1;
                for (i = left; i < right; i++)
                {
                    if (a[i - 1] > a[i])
                    {
                        z = a[i - 1];
                        a[i] = a[i - 1];
                        a[i - 1] = z;
                    }
                }
                right = last - 1;
            }
            foreach (int element in a)
                Console.Write(element + " ");
            Console.ReadKey();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim, 2019-05-16
@Matmode

Try i > left. Otherwise, with i=0, you get access to a non-existent element a[-1]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question