Rictus
Rictus

Reputation: 112

Sort an array of arrays in Erlang

I need to sort arrays but not classical ones. Moreover, in Erlang ! I'm talking about arrays where each element is an array of two integers.

For example : [ [6,0], [12,1], [5,2], [10,3] ]

I need this array to be sorted in function of the first element of each arrays Like this :

[ [5,2], [6,0], [10,3], [12,1] ]

First, I succeed with this :

-module(insertSort).
-export([insertion/1,insert/1,insert/2]).

insertion(L) -> lists:foldl(fun insert/2, [], L).

insert([]) -> [].

insert(X,[]) -> [X];
insert([],Y) -> [Y];

insert(X= [X1,_], L= [[H1,_] | _]) when X1 =< H1 -> [X|L];

insert(X,[H|T]) -> [H|insert(X, T)].

Sometimes, arrays are sorted. But I have two examples that gives me two weird cases:

First : [ [10,3], [5,2], [12,1], [6,0] ] become : [[[5,2], [6,0], [10,3], [12,1]]]]

Not bad but I can't work with that weird construction. It seems that I have an array, where there is an array inside, where there is all my two-elements arrays inside.

Second : [ [5,16], [11,12], [9,8], [16,4] ] become : [[[5,16], "\t\b","\v\f",[16,4]]]

Yes, really, with these \t\b..

I'm a beginner in Erlang but I succeed to do a lot of things by myself. My project is about Shank Algorithm, trying to solve y = a^x mod n where y, a and n are given.

Can you please help me by telling me what is wrong with my insertSort module ?

Thanks a lot, sorry for my english, I tried to do my best.

Upvotes: 1

Views: 559

Answers (3)

Łukasz Ptaszyński
Łukasz Ptaszyński

Reputation: 1689

I think problem is with line:

insert([],Y) -> [Y];

Y is already a sorted list so it should be returned as it is

insert([],Y) -> Y;

Erlang strings are list of integers so when your list is not really a string but contains code points of your specified encoding, then it is printed in string notation, but it's still a list. List [65,65,67,68] is equal to "ABCD". Try to type that list into your shell, it's just an erlang pretty printing... not accurate sometimes.

Upvotes: 1

Pascal
Pascal

Reputation: 14042

As I said in my comment, the sort function of the lists library does exactly what you want.

1> lists:sort( [ [6,0], [12,1], [5,2], [10,3] ]).
[[5,2],[6,0],[10,3],[12,1]]
2>

Upvotes: 1

RichardC
RichardC

Reputation: 10557

You probably shouldn't write your own sorting function. If lists:sort(List) isn't what you want for your use case, you could sort on only the first element of the sublists like this:

lists:sort(fun ([H1|_],[H2|_]) -> H1 =< H2 end,
           List)

Upvotes: 1

Related Questions