11 Replies - 318 Views - Last Post: 07 February 2013 - 06:09 PM Rate Topic: -----

#1 Debugging  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 07-February 13

Problem with sorting array from A-Z

Posted 07 February 2013 - 04:31 AM

Hello!

Im creating this register over pc games, very easy beginners programming, and i want the register to sort itsel from A to Z. Wich for should i be using and how do i implent that in this code below? Im really confused about this and sry for posting the whole code...Dunno what else to do :S




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

namespace ConsoleApplication2
{
    class Spelregister
    {

        static int antal = 0; // när man börjar finns det inga spel
        struct spel
        { 
            public int id;
            public string title;
            public string år;
            public string genré;
            public string studio;
            public string publisher;
        }
        static spel[] spelen = new spel[100]; // antalet spel vi kan lagra i vektorn



        static void Main(string[] args)
        {
            ladda();  //laddar spelen från static void ladda
            string svar = "1";
            

            while (1==1)
            {
                    Console.WriteLine("----------------");
                    Console.WriteLine("1 för sök");
                    Console.WriteLine("2 för lagra");
                    Console.WriteLine("3 för avsluta");
                    Console.WriteLine("----------------");
                svar = Console.ReadLine();
                if (svar == "1") // om svar = 1 sök
                {
                    svar = "4"; // endast där för att jag vill att den ska hoppa ur då man är fördig med sök och att det gammla svaret ligger kvar.
                    Console.WriteLine("----------------");
                    Console.WriteLine("1 för visa lista");
                    Console.WriteLine("2 för sök");
                    Console.WriteLine("3 för huvudmeny");
                    Console.WriteLine("----------------");
                    string söksvar = Console.ReadLine();

                    while (söksvar == "1" || söksvar == "2")
                    {
                        if (söksvar == "1") // om svar = 1 visa lista
                        {
                            skrivlista(); // hoppar till static void skrivlista

                        }
                        else if (söksvar == "2") // om svar = 2 sök
                        {

                            Console.WriteLine("Ange titel");
                            string finnsvar = Console.ReadLine();
                            sök(finnsvar); // hoppar ner till static void sök

                        }
                        Console.WriteLine("----------------");
                        Console.WriteLine("1 för visa lista");
                        Console.WriteLine("2 för sök");
                        Console.WriteLine("3 för huvudmeny");
                        Console.WriteLine("----------------");
                        söksvar = Console.ReadLine();
                    }
                }
                else if (svar == "2") //om svar = 2 lagra
                {

                    lagra(); // hoppar ner till static void lagra
                    Console.WriteLine("----------------");
                    Console.WriteLine("1 för sök");
                    Console.WriteLine("2 för lagra");
                    Console.WriteLine("3 för avsluta");
                    Console.WriteLine("----------------");
                    svar = Console.ReadLine();
                }
                else if (svar == "3")
                {
                    break;
                }

            }
            Console.WriteLine("Tack och hej!");

     
        }
        static void sök(string x)
        {
            for (int i = 1; i <= antal; i++)
            {
                if (spelen[i].title.ToUpper() == x.ToUpper())
                {
                    Console.WriteLine(spelen[i].title + " " + spelen[i].år + " " + spelen[i].genré + " " + spelen[i].studio + " " + spelen[i].publisher); // En for loop som hoppar över alla utom title
                }
            }
        }
        static void lagra()
        {
            Console.WriteLine("Ange titel");
            string title = Console.ReadLine();
            Console.WriteLine("Ange utgivningsår");
            string år = Console.ReadLine();
            Console.WriteLine("Ange genré");
            string genré = Console.ReadLine();
            Console.WriteLine("Ange studio");
            string studio = Console.ReadLine();
            Console.WriteLine("Ange publisher");
            string publisher = Console.ReadLine();

            antal = antal + 1;                              //lagrar antal i vektor
            spelen[antal].id = antal;
            spelen[antal].title = title;
            spelen[antal].år = år;
            spelen[antal].genré = genré;
            spelen[antal].studio = studio;
            spelen[antal].publisher = publisher;
        }
        static void skrivlista()
        {
            for (int i = 1; i <= antal; i++)
            {
                Console.WriteLine(spelen[i].title + " " + spelen[i].år + " " + spelen[i].genré + " " + spelen[i].studio + " " + spelen[i].publisher); // matar ur en lista på alla spel
            }
        }
        static void ladda() // bara för att ladda några lagrar ej
        {
            spelen[1].title = "battlefield";
            spelen[1].år = "2012";
            spelen[1].genré = "action";
            spelen[1].studio = "Dice";
            spelen[1].publisher = "EA Games";

            spelen[2].title = "minecraft";
            spelen[2].år = "2010";
            spelen[2].genré = "strategi";
            spelen[2].studio = "mojang";
            spelen[2].publisher = "mojang ab";

            spelen[3].title = "Diablo 3";
            spelen[3].år = "2012";
            spelen[3].genré = "RPG";
            spelen[3].studio = "Blizzard";
            spelen[3].publisher = "Blizzard";

            antal = 3;
        }
    }

}


This post has been edited by Skydiver: 07 February 2013 - 06:39 AM
Reason for edit:: Put in code tags. Please do this yourself in the future.


Is This A Good Question/Topic? 0
  • +

Replies To: Problem with sorting array from A-Z

#2 raghav.naganathan  Icon User is offline

  • Perfectly Squared ;)
  • member icon

Reputation: 408
  • View blog
  • Posts: 1,440
  • Joined: 14-September 12

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 04:51 AM

I believe this is C# and not C/C++

Mod: Can you please move this to the C# forum.

Thanks

Regards,
Raghav
Was This Post Helpful? 0
  • +
  • -

#3 Debugging  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 07-February 13

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 05:14 AM

View Postraghav.naganathan, on 07 February 2013 - 04:51 AM, said:

I believe this is C# and not C/C++

Mod: Can you please move this to the C# forum.

Thanks

Regards,
Raghav


When i made the post i made it from the first page you picked after the register. And i couldnt find the subject C#, only c/c++ so i went for it :)
Was This Post Helpful? 0
  • +
  • -

#4 sepp2k  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2017
  • View blog
  • Posts: 3,046
  • Joined: 21-June 11

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 05:26 AM

Moved to C#.

View PostDebugging, on 07 February 2013 - 01:14 PM, said:

When i made the post i made it from the first page you picked after the register. And i couldnt find the subject C#, only c/c++ so i went for it :)/>


It's 4 down from C/C++:

C/C++
VB6
Java
VB.NET
C#
Was This Post Helpful? 0
  • +
  • -

#5 pharylon  Icon User is offline

  • D.I.C Head

Reputation: 40
  • View blog
  • Posts: 83
  • Joined: 01-September 12

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 07:05 AM

So, first, make sure you put your code in the code markers. It makes it MUCH easier to read.

That being said, making objects that know how to compare themselves to each other and sort them is generally not something you do with Arrays, but with List<T> which is probably a bit more advanced than where you're at (they're like much more flexible and advanced arrays, to simplify a bit).

I can't think if any way to easily sort an Array. Here's why:

Each string has a CompareTo method. So if you have

string string1 = "Alpha";
string string2 = "Bravo";

int higherOrLower = string1.ComareTo(string2);



higherOrLower in this case will be -1 if lower, 0 if the same, and 1 if higher. You can use that to compare any two strings easily. With an array, you could create a loop that does something like:

        static void Main(string[] args)
        {
            string[] test = new string[] {"Bravo", "Alpha", "Delta"};
            string firstString = test[0];
            foreach (string s in test)
            {
                if (s.CompareTo(firstString) < 0)
                    firstString = s;
            }

            Console.WriteLine(firstString);
            Console.ReadKey();
        }



This code will write "Alpha." So you've got the first string alphabetically... but then how do you get the second? Well, you could easily find the second if, once you found the first, you removed it from the array.

So, the best way would probably be to create a new array, and then each time you find the first string, you set it as the first item in your new array and remove it from the old. Next time you search that old array, you'll find the new first string (formerly the second) and repeat.

Here's the problem: manipulating normal arrays is a huge pain. You can do it - there are ways - but they're pretty hacky. The easiest thing to do is switch from a normal Array to an ArrayList. These function very similar to regular arrays, but have an Add() and Remove() function, so they can be dynamically resized. So you'd put your items in an ArrayList, find the first alphabetically, and then Add() it as the first item in your new array and Remove() it form the old. Then do it again until the old array is empty. Then you can change the original array's reference to the new one likeoldArrayName = newArrayName so the rest of the program doesn't have to worry about two different arrays (and as a bonus, it'll make that old empty array get garbage collected).

And done!

This post has been edited by pharylon: 07 February 2013 - 07:15 AM

Was This Post Helpful? 0
  • +
  • -

#6 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 2890
  • View blog
  • Posts: 9,597
  • Joined: 12-December 12

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 07:21 AM

Quote

So, the best way would probably be to create a new array, and then each time you find the first string, you set it as the first item in your new array and remove it from the old. Next time you search that old array, you'll find the new first string (formerly the second) and repeat.

This is the least efficient way to sort an array.. There are many ways to sort if you wish to study this subject: wiki. Might take a few years though :)

Or..

Array.Sort(spelen, delegate(spel x, spel y) { return string.Compare(x.title, y.title); });

Was This Post Helpful? 0
  • +
  • -

#7 Anthonidas  Icon User is offline

  • D.I.C Head

Reputation: 30
  • View blog
  • Posts: 215
  • Joined: 25-April 11

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 07:25 AM

as already said from pharylon just use lists. they are more advanced and easyer to use. you can create entire classes to structure your lists and you can sort them with a simple command .Sort()

have a look here: http://msdn.microsof...y/6sh2ey19.aspx

This post has been edited by Anthonidas: 07 February 2013 - 07:26 AM

Was This Post Helpful? 0
  • +
  • -

#8 pharylon  Icon User is offline

  • D.I.C Head

Reputation: 40
  • View blog
  • Posts: 83
  • Joined: 01-September 12

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 07:26 AM

Quote

So, the best way would probably be to create a new array, and then each time you find the first string, you set it as the first item in your new array and remove it from the old. Next time you search that old array, you'll find the new first string (formerly the second) and repeat.


Well, yes. I know. But he's even newer than I am, so I knew he needed a simple way to do it. :)/>/>

It's also possible that he's doing this for an assignment, and the professor wants him to think through sorting more than just using Lists.

Actually, also, I just realized that ArrayList has a Sort() function too.... heh. :)

This post has been edited by pharylon: 07 February 2013 - 07:34 AM

Was This Post Helpful? 0
  • +
  • -

#9 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 2890
  • View blog
  • Posts: 9,597
  • Joined: 12-December 12

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 07:31 AM

View Postpharylon, on 07 February 2013 - 07:26 AM, said:

Well, yes. I know. But he's even newer than I am, so I knew he needed a simple way to do it. :)

It's also possible that he's doing this for an assignment, and the professor wants him to think through sorting more than just using Lists and sorting.

Fair enough :)
Was This Post Helpful? 0
  • +
  • -

#10 Debugging  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 07-February 13

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 10:05 AM

First of all thanks for all the answers! And no this isnt an assignment its my own small little learning project.
Im glad to already see users diving into my little "problem" !

This seems like the way to do it, i will try it later tonight!


[quote name='andrewsw' date='07 February 2013 - 07:21 AM' timestamp='1360246899' post='1798558']

Quote

Or..

Array.Sort(spelen, delegate(spel x, spel y) { return string.Compare(x.title, y.title); });


First of all thanks for all the answers! And no this isnt an assignment its my own small little learning project.
Im glad to already see users diving into my little "problem" !

This seems like the way to do it, i will try it later tonight!


[quote name='andrewsw' date='07 February 2013 - 07:21 AM' timestamp='1360246899' post='1798558']

Quote

Or..

Array.Sort(spelen, delegate(spel x, spel y) { return string.Compare(x.title, y.title); });


And where the heck do i edit my reply!? Am i that blind?
Was This Post Helpful? 0
  • +
  • -

#11 pharylon  Icon User is offline

  • D.I.C Head

Reputation: 40
  • View blog
  • Posts: 83
  • Joined: 01-September 12

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 05:47 PM

By the way, I just thought I'd mention something: Although it's hidden from you, Lists actually use CompareTo() when you call the Sort() method. If you you put an object besides a string or integer into a List, all you have to do is implement the ICompareable<T> interface for that class (IComparable<T> features one method and one method only - ComapreTo()). Then you can Sort() any type of class that you create.

As an example - and I happen to have this handy - here's the CompareTo method for a playing card class.

        public int CompareTo(Card other)
        {
            if (this.Value > other.Value)
                return 1;
            else if (this.Value < other.Value)
                return -1;
            else
            {
                if (this.Suit > other.Suit)
                    return 1;
                else if (this.Suit < other.Suit)
                    return -1;
                else return 0;
            }
        }


(Suit and Value in the code above are enums. Suit is "club," "spade," etc and Value is "King," "Ace," or "Three," etc).

So, just like with that string in the example I mentioned in my first post, if you called cardA.CompareTo(cardB) it'd return an integer - either -1 if cardA was "less than" cardB, 0 for "equal to" or 1 for "greater than". So I've built my own ComapreTo method for the cards.

The cool trick is, now if I create a List<Card>, I could call List<Card>.Sort() and that List would automagically be sorted as per the rules I defined in the Card classs's CompareTo() method! Anyway, just thought you might be interested to know that. :)/>

This post has been edited by pharylon: 07 February 2013 - 06:01 PM

Was This Post Helpful? 0
  • +
  • -

#12 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2216
  • View blog
  • Posts: 9,352
  • Joined: 29-May 08

Re: Problem with sorting array from A-Z

Posted 07 February 2013 - 06:09 PM

Tutorial on Custom Sorting
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1