Jump to content

Creating different sorting algorithm! need help to use the correct parameters!!!

- - - - -

  • Please log in to reply
1 reply to this topic

#1
owh786

owh786

    Newbie

  • Members
  • Pip
  • 7 posts
Current Java code:
import java.util.Random;
public class RandomArray
{
	public static void main(String[] args)
	{
		randArray();
	}
	public static void randArray()
	{
		Random rand = new Random();
		rand.setSeed(System.currentTimeMillis());
		
		int[] x = new int[10];
		for (int i=0; i<x.length; i++)
			{
				x[i] = Math.abs(rand.nextInt() % 256);
			}
		showArray(x);
	}
	public static void showArray(int[] x)
	{
		System.out.println("This is the random number from the list:");
		for (int i=0; i<x.length; i++)
		{
			System.out.print(x[i]+" ");
		}
	}
}

Above code works successfully, to create an arraylist from a random generating and displaying the array list.

But i am having difficulty to call a sorting method to sort the random items in the list.

Code below is the sorting method:
import java.util.*;
public class ThreeSorts
{
	private static ArrayList<Integer> CopyArray(ArrayList<Integer> a)
	{
		ArrayList<Integer> resa = new ArrayList<Integer>(a.size());
		for(int i=0;i<a.size();++i) resa.add(a.get(i));
		return(resa);
	}
	public static ArrayList<Integer> SortA(ArrayList<Integer> a)
	{
		ArrayList<Integer> array = CopyArray(a);
		int n = a.size(),i;
		boolean noswaps = false;
		
		while (noswaps == false)
		{
			noswaps = true;
			for(i=0;i<n-1;++i)
			{
				if (array.get(i) < array.get(i+1))
				{
					Integer temp = array.get(i);
					array.set(i,array.get(i+1));
					array.set(i+1,temp);
					noswaps = false;
				}
			}
		}
		return(array);
	}
}

so i need help calling the method, but don't know how to use the correct parameters!!!! :s
Thank you :)

#2
SgtSnyder

SgtSnyder

    Newbie

  • Members
  • Pip
  • 5 posts
  • Location:New Jersey
The sorting algorithm looks good to me. To integrate the two pieces of code the randArray needs to use arraylists or SortA needs to take an array as a parameter, because the two are not interchangeable.

In the randArray function you could declare x as an ArrayList instead of an array to make it compatable with your sorting algorithm, or have the argument a be a normal int[]. Just some small modification to either piece of code




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users