Sortowanie tablic (System.Array)

0

Witam serdecznie. Staram się napisać program, który wczytuje z pliku ciąg liczb naturalnych a następnie je sumuje w odpowiedni sposób. Mam kawałek programu który wczytuje mi z pliku do tablicy elementy ale typu string. I sortowanie nie odbywa się tak jak powinno, bo jak np mamy liczby 1,2,6,11,7 to wynik sortowania wyglądać będzie następująco: 1,11,2,6,7. Zastanawiam się czy nie stworzyć na początku tablicy Int[] ale też do końca nie wiem jak :/ Proszę o ewentualne sugestie ;)

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

namespace System_array
{
public class SamplesArray  
{
    public static void Main()
    {
        String[] myArr = File.ReadAllLines("in.txt");

        // Displays the values of the Array.
        Console.WriteLine("The Array initially contains the following values:");
        PrintIndexAndValues(myArr);

        // Sorts the entire Array using the default comparer.
        Array.Sort(myArr);
        Console.WriteLine("After sorting the entire Array using the default comparer:");
        PrintIndexAndValues(myArr);
    }

   public static void PrintIndexAndValues( String[] myArr )  
   {
      for ( int i = 0; i < myArr.Length; i++ )  
      {
         Console.WriteLine( "   [{0}] : {1}", i, myArr[i] );
      }
      Console.WriteLine();
      Console.ReadKey();
   }
}
}

Fragment kodu jest zaczerpnięty ze stronki MSDN...

0

Możesz na przykład podać swoją metodę porównującą do metody sortowania:

string[] data = new string[] { "1", "2", "7", "21", "11" };
Array.Sort<String>(data, delegate(string a, string b) { return Convert.ToInt32(a).CompareTo(Convert.ToInt32(b)); });
Array.ForEach<String>(data, delegate(string item) { Console.WriteLine(item); });
0
beast_metal napisał(a)

Zastanawiam się czy nie stworzyć na początku tablicy Int[] ale też do końca nie wiem jak
To by było najlepsze rozwiązanie:

List<int> liczby;
foreach(string line in File.ReadAllLines("in.txt")) 
   liczby.Add(Int32.Parse(line));
liczby.Sort();
0

Jeśli chcielibyśmy zostać przy tablicach to możemy to zrobić w taki sposób:

string[] data = new string[] { "1", "2", "7", "21", "11" };
int[] result = Array.ConvertAll<String, Int32>(data, delegate(String item) { return Convert.ToInt32(item); });
Array.ForEach<int>(result, delegate(int item) { Console.WriteLine(item); });
0

adf88 skorzystałem z twojego fragmentu kodu i napisałem takie coś:

using System;
using System.Collections.Generic;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path_in = @".\in.txt";
        string path_out = @".\out.txt";

        using (StreamReader sr = new StreamReader(path_in))
        {
            using (StreamWriter wr = new StreamWriter(path_out))
            {
                List<int> liczby = new List<int>();
                foreach (string linie in File.ReadAllLines(path_in))
                    liczby.Add(Int32.Parse(linie));
                liczby.Sort();

                foreach (int linie in liczby)
                {
                    Console.WriteLine(linie);
                    wr.WriteLine(linie);
                }
                Console.ReadKey();
            }
        }
    }
}

Działa prawidłowo _

mykhaylo, pierwszy fragment kodu wykorzystałem i działa poprawnie :D, oto mój wynik:

using System;
using System.Collections.Generic;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path_in = @".\in.txt";
        string path_out = @".\out.txt";

        using (StreamReader sr = new StreamReader(path_in))
        {
            using (StreamWriter wr = new StreamWriter(path_out))
            {
                string[] data =  File.ReadAllLines(path_in);
                Array.Sort<String>(data, delegate(string a, string b) { return Convert.ToInt32(a).CompareTo(Convert.ToInt32(b)); });
                Array.ForEach<String>(data, delegate(string item) { Console.WriteLine(item); });
                Console.ReadKey();

            }
        }
    }
}

I tak samo z drugim fragmentem kodu ;)

using System;
using System.Collections.Generic;
using System.IO;

public class Example
{
    public static void Main()
    {
        string path_in = @".\in.txt";
        string path_out = @".\out.txt";

        using (StreamReader sr = new StreamReader(path_in))
        {
            using (StreamWriter wr = new StreamWriter(path_out))
            {
                string[] tab = File.ReadAllLines(path_in);
                int[] tab2 = Array.ConvertAll<String, Int32>(tab, delegate(String linia)
                { 
                    return Convert.ToInt32(linia); });
                Array.Sort(tab2);
                Array.ForEach<int>(tab2, delegate(int linia) { Console.WriteLine(linia); });
                Console.ReadKey();

            }
        }
    }
}

I mam jeszcze pytanko, proszę o podpowiedź z jakiego parametru należało by skorzystać aby z wczytywanego pliku był pobierany ciąg liczb, a nie tak jak mam teraz, że jedna musi być pod drugą.

0

Możesz wczytać cały plik lub jego część, jeśli plik jest duży a następnie rozdzielić liczby jakimś z góry zdefiniowany i znanym znakiem. Otrzymujesz tablicę i postępujesz dalej jak powyżej. W poniższym przykładzie zakładam że liczby w pliku są rozdzielone spacją:

string data = File.ReadAllText(fileName);
string[] numbers = data.Split(' ');
int[] result = Array.ConvertAll<String, Int32>(numbers, delegate(String item) { return Convert.ToInt32(item); });
Array.Sort<int>(result);
Array.ForEach<int>(result, delegate(int item) { Console.WriteLine(item); });

Pewnie sam zauważyłeś że idea niczym się nie różni niż przedtem. Poprzednio liczby były rozdzielone znakiem nowej linii a teraz są rozdzielone znakiem spacji. Poprzednio użyłeś metody File.ReadAllLines - teraz możesz użyć File.ReadAllText.

1 użytkowników online, w tym zalogowanych: 0, gości: 1