5/14/2012

Thuật toán sắp xếp mảng

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

namespace ConsoleApplication1
{
    class Question1
    {
        private int[] arrA;
        public string FindNumber(int n)
        {
            string result = "";
            try
            {
                int i;
                int j;
                int tmp;
                arrA = new int[n];
                for (i = 0; i < n; i++)
                {
                    Console.Write("\n\tNhap vao phan tu thu " + (i + 1)+": ");
                    arrA[i] = int.Parse(Console.ReadLine());
                }

                for (i = 0; i < n - 1; i++)
                {
                    for (j = i + 1; j < n; j++)
                    {
                        if (arrA[i] > arrA[j])
                        {
                            tmp = arrA[i];
                            arrA[i] = arrA[j];
                            arrA[j] = tmp;    //doi cho a[i] va a[j]
                        }
                    }                                    
                }
                // in ra mang da sap xep theo thu tu tang dan
                for (i = 0; i < n; i++)
                {                    
                    result += arrA[i]+" ";
                    //Sap xep giam dan
                    //result += arrA[n-(i+1)]+" ";
                }                
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }

    }
}

---------------------------------------------------------------------------------------

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Nhap so phan tu cua mang so nguyen:");
            int n = int.Parse(Console.ReadLine());

            Question1 q = new Question1();
            string result = q.FindNumber(n);
            Console.WriteLine("KET QUA SAP XEP TANG DAN: "+result);
            Console.ReadLine();
        }
    }
}

Cách 2

        /// <summary>

        /// Sorting an input array

        /// the output would be another array with sorted by ascending

        /// for example : input: 1,3,2 -> the output would be 1,2,3

        /// </summary>

        /// <param name="Str_ListBox">the input array</param>

        /// <returns>the output with sorted items</returns>

        public static string GetSortedArray(string sourceString)

        {

            List<int> lstSource = new List<int>();

            foreach (string s in sourceString.Split(','))

            {

                lstSource.Add(int.Parse(s));

            }

            lstSource.Sort();

            return ConvertListObjectToString(lstSource);

        }

Categories:
If You Enjoyed This Post Please Take 5 Seconds To Share It.

0 comments:

Post a Comment

 
  • Followers