插入随机数 [英] Insertion Random Numbers

查看:80
本文介绍了插入随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

namespace Insertion_Random
{
    public class Insertionsort
    {
        private int[] item;

        public Insertionsort(int[]i)
        {
            item = i;
        }
        //Return the size of the array of data to sort
        public static int GetSize()
        {
            Console.WriteLine("Enter the number of data items: ");
            return int.Parse(Console.ReadLine());
        }
        /* Return the data array , either
         * entered by the user,or
         * randomly selected.
         *
         */
        public static int[] GetData(int size)
        {
            int[] item = new int[size];
            Console.Write("Enter'Y' to enter data,'N'for random data: ");
            string enter = Console.ReadLine();
            if (enter.ToUpper() == "Y")
                for (int i = 0; i < size; i++)
                {
                    Console.Write("Enter item[" + i + "]: ");
                    item[i] = int.Parse(Console.ReadLine());
                }
            else
            {
                Random random = new Random();
                for (int i = 0; i < size; i++)
                    item[i] = random.Next(100);
            }
            return item;
        }
        /*Insert the next element in the correct position
         * with respect to itn predecensors.
         */
        public void InsertNext(int i)
        {
            int current = item[i];
            int j = 0;
            while(current>item[j])j++;
            for (int k = i;k>j;k--)
                item[k] = item[k-1];
            item[j]=current;
        }
        //Inserts each element
        public void Sort()
        {
            for (int i = 1; i < item.Length; i++)
            {
                InsertNext(i);
            }
        }
        //Gets and sorts an array of integer data.
        public static void Main()
        {
            int size = GetSize();
            int[] item = GetData(size);
            
            ArrayCopy.Display("The data to sort is ", item);
            Insertionsort s = new Insertionsort(item);
            s.Sort();
            ArrayCopy.Display("The sort data is ", item);



        }





    }
}

推荐答案

我刚刚修改了您的主要代码块,如下图所示:


I just modified your main block like follows it is working


 int size = GetSize();
 int[] item = GetData(size);

// ArrayCopy.Display("The data to sort is ", item);
 Insertionsort s = new Insertionsort(item);
 s.Sort();
 //ArrayCopy.Display("The sort data is ", item);

 item = s.item;
 for (int i = 0; i < item.Length; i++)
     Console.WriteLine(item[i]);
 Console.ReadLine();


这篇关于插入随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆