java


Sorting a nX3 matrix (Most efficient way)


I am writing code for Mo's algorithm with update in JAVA , so in this we have to order in ascending order an ArrayList of N X 3 matrix in this way
The ArrayList is of the form
Ai,Bi,Ci
For example:
1,2,3
2,3,4
1,2,1
2,3,5
so to sort them , first look for all the Ai, if there is a clash like in Ai of 1,2,3 and 1,2,1 ,then look for Bi,if there is a clash ,then look for Ci, and sort them accordingly .
Sorted array
1,2,1
1,2,3
2,3,4
2,3,5
So is there any data structure to sort them without having to write a big long piece of code ?
Those who are asking for my code in comments-->
// RIGHT NOW I HAVEN'T MADE AN N X # MATRIX ,WHAT I HAVE DONE IS TAKEN 3 ARRAYLISTS , yes I WILL CHANGE IT INTO A SINGLE ARRAYLIST OF SIZE N X 3
public class MoSAlgorithmUpdates {
public static void main(String[] args) throws IOException {
//finding no of distict numbers
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
String str;
//Taking the Array Now
str=br.readLine();
ArrayList<Integer> arr=new ArrayList<Integer>();
StringTokenizer st = new StringTokenizer(str," ");
while(st.hasMoreTokens())
{
arr.add(Integer.parseInt(st.nextToken()));
}
// Total q queries including updates + finding distinct numbers
int Q;
str = br.readLine();
Q = Integer.parseInt(str);
int[] q1=new int[Q];
int[] q2=new int[Q];
int[] q3=new int[Q];
int[] q4=new int[Q];
ArrayList<Integer> query1=new ArrayList<Integer>();// RIGHT NOW I HAVEN'T MADE AN N X # MATRIX ,WHAT I HAVE DONE IS TAKEN 3 ARRAYLISTS , yes I WILL CHANGE IT INTO A SINGLE ARRAYLIST OF SIZE N X 3
ArrayList<Integer> query2=new ArrayList<Integer>();// RIGHT NOW I HAVEN'T MADE AN N X # MATRIX ,WHAT I HAVE DONE IS TAKEN 3 ARRAYLISTS , yes I WILL CHANGE IT INTO A SINGLE ARRAYLIST OF SIZE N X 3
ArrayList<Integer> query3=new ArrayList<Integer>();// RIGHT NOW I HAVEN'T MADE AN N X # MATRIX ,WHAT I HAVE DONE IS TAKEN 3 ARRAYLISTS , yes I WILL CHANGE IT INTO A SINGLE ARRAYLIST OF SIZE N X 3
ArrayList<Integer> update1=new ArrayList<Integer>();
ArrayList<Integer> update2=new ArrayList<Integer>();
ArrayList<Integer> update3=new ArrayList<Integer>();
//int[] update1=new int[Q];
int noofupdates=0;
//noofupdates=time
for(int i2=0;i2<Q;i2++)
{
str=br.readLine();
StringTokenizer st2 = new StringTokenizer(str," ");
q1[i2]=Integer.parseInt(st2.nextToken());
q2[i2]=Integer.parseInt(st2.nextToken());
q3[i2]=Integer.parseInt(st2.nextToken());
if(q1[i2]==1)
{
query1.add(q2[i2]);
query2.add(q3[i2]);
query3.add(noofupdates);
}
else
{
update1.add(q2[i2]);
update2.add(q3[i2]);
noofupdates++;
}
}
}
}
LAST QUERY-->
IN Mo's Algorithm with updates, we arrange the ArrayList by
int sqrt = Math.sqrt(N) // N is the length of ArrayList containing all the
// numbers from which range queries have to be told
now sort the . numbers as
Now let's say L,R,time are for eg
1,3,3
2,3,4
2,1,1
2,3,5
So sorting them by L,R,time returns result as
Sorted array
1,3,3
2,1,1
2,3,4
2,3,5
Now sorting them by has to be done ,how can be that done ? the final output has to be like without square root that is the values L,R,time should not change but sorting has to be done with . How to achieve that -- ?
The final output may look like this depending on the value of N
2,1,1
1,3,3 //Very Imp see this it is sorted
2,3,4
2,3,5
Radix sort
https://en.wikipedia.org/wiki/Radix_sort
You can use default sort method of collections
Collections.sort(yourArrayN2, comparator);
You should define comparator which compares both arrays starting from first elements (we assume that these arrays / lists have the same size; otherwise you will modify the comparator).
Comparator:
public class ListComparator implements Comparator<List<Integer>> {
#Override
public int compare(List<Integer> list1, List<Integer> list2) {
if (list1 == null || list2 == null || list1 == list2) {
throw new IllegalArgumentException();
}
int size = list1.size();
if (size != list2.size()) {
throw new IllegalArgumentException();
}
for (int i = 0; i < size; i++) {
int delta = list1.get(i) - list2.get(i);
if (delta != 0) {
return delta;
}
}
return 0;
}
}
And its usage
public class App {
public void execute() {
List<List<Integer>> list2D = make2DList();
printList2D(list2D);
System.out.println("\n");
Collections.sort(list2D, new ListComparator());
printList2D(list2D);
}
//This is where you create your 2D list. It can be read from file, etc.
private List<List<Integer>> make2DList() {
List<List<Integer>> res = new ArrayList<>(3);
res.add(makeList(1,2,3));
res.add(makeList(2,3,4));
res.add(makeList(1,2,1));
res.add(makeList(2,3,5));
return res;
}
private List<Integer> makeList(Integer ... numbers) {
List<Integer> res = new ArrayList<>();
for (Integer i : numbers) {
res.add(i);
}
return res;
}
private void printList2D(List<List<Integer>> list2D) {
for (List<Integer> list : list2D) {
printList(list);
}
}
private void printList(List<Integer> list) {
int size = list.size();
int lastIndex = size - 1;
for (int i = 0; i < lastIndex; i++) {
System.out.print(list.get(i) + ", ");
}
System.out.print(list.get(lastIndex) + "\n");
}
}
It prints
1, 2, 3
2, 3, 4
1, 2, 1
2, 3, 5
1, 2, 1
1, 2, 3
2, 3, 4
2, 3, 5

Related Links

IllegalArgumentException when writing bytes to file
content layout navigation and linkable urls
Java execution randomly stopping
Setting ImageView at certain positions in a ListView based on CheckBox
How can I make this faster, without making it multi-threaded?
How to Have my JLabels Display Strings stored in my ArrayList?
how to display this notification in Android?
Android Java : How to propertly close ObjectInputStream and FileInputStream
Apache Spark join index optimization
What is the Compatible version of Spring-security with spring-4.3.0-release?
Jsoup with JavaScript dependent web page?
Fragment Backstacking correctly
Is there any way to retrieve the executed query from java ResultSet?
Hitting OBIEE presentation Server URL with Java
Alter table modify <column> does not work in Hsqldb with Oracle syntax
Add logo to javadoc to top left corner using doclava

Categories

HOME
cakephp
ibm-bluemix
sendgrid
vim
jdo
coq
minimum-spanning-tree
path-finding
session
spagobi
tizen-web-app
ezpublish
indesign
adfs
offline
imacros
windows-phone-7
fallback
ibm-odm
iron-router
dosgi
systemc
graphlab
aurigma
invantive-sql
undefined
database-replication
visjs
tokenize
crystal-reports-2010
xpages-ssjs
selectedindexchanged
windows-error-reporting
ping
jspm
c++-amp
fog
geopositioning
io-redirection
devextreme
disassembling
occlusion
objectlistview
awt
sfdc
nand2tetris
slick-3.0
sencha-touch-2.3
sqlclient
spring-cache
lync-client-sdk
firmata
infix-notation
multi-level
qpid
two-factor-authentication
netmq
reactive-banana
operation
sortedlist
mmc
census
pretty-print
lustre
relocation
wordpress-theme-customize
titanium-modules
google-reader
eol
p4java
valueconverter
xceed-datagrid
resty-gwt
.aspxauth
dir
inbox
listings
coverflow
dotnetnuke-5
eclipse-memory-analyzer
buster.js
sqlperformance
http-unit
browser-detection
objective-c-2.0
jquery-ui-layout
hgsubversion
pydot
self-extracting
xsdobjectgen
ncqrs
mediarss

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile