The Artima Developer Community
Sponsored Link

Java Answers Forum
MergeSort Trouble

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Michael

Posts: 1
Nickname: michael20
Registered: Mar, 2005

MergeSort Trouble Posted: Mar 13, 2005 4:30 PM
Reply to this message Reply
Advertisement
Hi i am trying to create a game of scrabble using several different interfaces. I am currently working on the board, and am wanting to sort the words which are put on the board in alphabetical order. I have attempted to do this by mergesort but its not working and i cant work out why.
Here is my code. Can anyone tell me where i am going wrong? And how i can change it to correct it?
Many thanks

/*
* This method merges each half of the arrays in to an *alphabetical order
*/

private static void merge(String words[], String temp[], int low, int middle, int high)

{
int ri = low;
int ti = low;
int di = middle;

while (ti < middle && di <= high) {
if ( words.length < temp.length)
words[ri++] = words[di++];

else
words[ri++] = temp[ti++];
}
while (ti < middle) {
words[ri++] = temp[ti++];
}
}

/*
* This sorts the array using the merge sort algorithim
*/

private static void mergeSortRecursive(String words[], String temp[], int low, int high) {

int n = high - low + 1;
int middle = low + n/2;
int i;

if (n < 2) return;

for (i = low; i < middle; i++) {

temp = words;
}

mergeSortRecursive(temp, words, low, middle-1);

mergeSortRecursive(words,temp,middle,high);

merge(words,temp,low,middle,high);

}

public String[] getWords() {

String[] words = new String[100];
String string = "";
int k = 0;

for (int y = 0; y<getBoardSize(); y++) {

for (int x = 0; x<getBoardSize(); x++) {

Tile tile = getTile(x, y);

if(tile != null) {

string = string + tile.getLetter();
}
else {

if(string.length() >= 2) {
words[k] = string;
k++;
}
string = "";
}

}
}

for(int x = 0; x < getBoardSize(); x++) {

for(int y = 0; y < getBoardSize(); y++) {

Tile tile1 = getTile(x, y);

if(tile1 != null) {

string = string + tile1.getLetter();
}
else {

if(string.length() >= 2) {
words[k] = string;
k++;
}
string = "";
}

}

}
mergeSortRecursive(words, new String[k], 0, k-1);

return words;

}

Topic: Java program structure Previous Topic   Next Topic Topic: BufferedReader

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use