Sorting a randomized array in Java - java

I am trying to make an app for sorting a randomized array
I made some code and I can not see what is wrong with it that it returns wrong values
Notes: I am trying to learn programming. So don't suggest whole different ways of solving the problem. I just want to see what is wrong with this code so I can get better.
What RandomArrayCreator.create() returns is just an array of numbers in randomized order.
public class ArraySorter
{
public static void main(String[] args)
{
int[] siyahi = RandomArrayCreator.create();
int[] siralanmish = new int[siyahi.length];
for (int i=0;i<siyahi.length;i++)
{
for (int j=0;j<siyahi.length;j++)
{
for (int k=j+1;k<siyahi.length;k++)
{
if (siyahi[k]<siyahi[j]) j=k;
}
siralanmish[i]=siyahi[j];
siyahi[j]=siyahi.length+1;
}
System.out.println(siralanmish[i]);
}
}
}

I know you did not want suggestions but I'm going to offer one anyway.
Hopefully this will help guide you along the way, but still allow you to come up with your own solution.
Sort smallest to biggest.
did I have swap an element?
while I swapped an element
assume I did not swap an element
for element i in the array
is i > i+1?
if yes
swap the elements
I did swap an element
else
do nothing

Given that you mentioned you wanted to learn how to improve your current program, here are minimalist changes that will have your code produce a sorted array.
A few notes on the changes:
1.
if (siyahi[k]<siyahi[j]) j=k;
This I assume is for trying to swap the values at each indexes. Instead you are assigning the value of k to j which will cause problems with the entire for loop. I replaced this with the following:
if (siyahi[k]<siyahi[j])
{
int temp = siyahi[j];
siyahi[j] = siyahi[k];
siyahi[k] = temp;
}
This creates a temporary variable to store one of the values so that you can swap the value at each index without losing one of your values.
2.
siralanmish[i]=siyahi[j];
This was replaced with:
siralanmish[j]=siyahi[j];
This allows you to directly copy the values from the same index from the source array to the target array.
3.
siyahi[j]=siyahi.length+1;
This code will just fill up your array with the value of length+1 for your original array and you will lose your other values.
Your code with the fixes are below:
public class ArraySorter
{
public static void main(String[] args)
{
int[] siyahi = RandomArrayCreator.create();
int[] siralanmish = new int[siyahi.length];
for (int i=0;i<siyahi.length;i++)
{
for (int j=0;j<siyahi.length;j++)
{
for (int k=j+1;k<siyahi.length;k++)
{
if (siyahi[k]<siyahi[j])
{
int temp = siyahi[j];
siyahi[j] = siyahi[k];
siyahi[k] = temp;
}
}
siralanmish[j]=siyahi[j];
}
System.out.println(siralanmish[i]);
}
}

Related

Making all values in an array unique

Im making a small school project, keep in mind i'm a beginner. Im gonna make a small system that adds member numbers of members at a gym to an array. I need to make sure that people cant get the same member number, in other words make sure the same value doesnt appear on serveral index spots.
So far my method looks like this:
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
if(memberNr.equals(mNr)){
throw new IllegalArgumentException("The member is already in the system");
}
else{
memberNr[count++] = mNr;
}
}
While having a contructor and some attributes like this:
int[] memberNr;
int arraySize;
int count;
public TrainingList(int arraySize){
this.arraySize = arraySize;
this.memberNr = new int[arraySize];
}
As you can see i tried using equals, which doesnt seem to work.. But honestly i have no idea how to make each value unique
I hope some of you can help me out
Thanks alot
You can use set in java
Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored.
mport java.util.*;
public class Set_example
{
public static void main(String[] args)
{
// Set deonstration using HashSet
Set<String> hash_Set = new HashSet<String>();
hash_Set.add("a");
hash_Set.add("b");
hash_Set.add("a");
hash_Set.add("c");
hash_Set.add("d");
System.out.print("Set output without the duplicates");
System.out.println(hash_Set);
// Set deonstration using TreeSet
System.out.print("Sorted Set after passing into TreeSet");
Set<String> tree_Set = new TreeSet<String>(hash_Set);
System.out.println(tree_Set);
}
}
public void members(int mNr){
if(arraySize < memberNr.length){
throw new IllegalArgumentException("There are no more spots available");
}
//You need to loop through your array and throw exception if the incoming value mNr already present
for(int i=0; i<memberNr.length; i++){
if(memberNr[i] == mNr){
throw new IllegalArgumentException("The member is already in the system");
}
}
//Otherwise just add it
memberNr[count++] = mNr;
}
I hope the comments added inline explains the code. Let me know how this goes.
Hey you can’t directly comparing arrays (collection of values with one integer value)
First iterate the element in membernr and check with the integer value

Android II JAVA Sorting An ArrayList of an object

First of all sorry if my English bad, its not my first language..
I'm working on and android app project, that needed to sort ArrayList of an object..so I made this method to deal with that...
Lets say that I have an object of Restaurant that will contain this data:
private String name;
private float distance ;
And I sort it using the value of the variable distance from lowest to highest:
public void sort(RArrayList<RestaurantData> datas) {
RestaurantData tmp = new RestaurantData();
int swapped;
boolean b = true;
while (b) {
swapped = 0;
for (int i = 0; i < datas.size()-1; i++) {
if (datas.get(i).getDistance() > datas.get(i+1).getDistance()) {
tmp = datas.get(i);
datas.set(i, datas.get(i+1));
datas.set(i+1, tmp);
swapped = 1;
System.err.println("Swapped happening");
}
}
if (swapped == 0) {
System.err.println("Swapped end");
break;
}
}
But when i try the program..the result of an ArrayList is still random, is there any problem with my logic to sort the ArrayList of an object..
Please Help...Thankyou..
Why not use the Collections.sort method?
Here's how you could do it in your project:
public void sort(RArrayList<RestaurantData> datas) {
Collections.sort(datas, new Comparator<RestaurantData>() {
#Override
public int compare(RestaurantData lhs, RestaurantData rhs) {
return lhs.getDistance() - rhs.getDistance();
}
});
}
The above solution is a bit "destructive" in the sense that it changes the order of the elements in the original array - datas. If that's fine for you go ahead and use it. Personally I prefer things less destructive and if you have the memory to spare (meaning your array is small) you could consider this solution which copies the array before sorting. It also assumes your RArrayList is an implementation of ArrayList or backed up by it:
public List<RestaurantData> sort(RArrayList<RestaurantData> datas) {
// Create a list with enough capacity for all elements
List<RestaurantData> newList = new RArrayList<RestaurantData>(datas.size());
Collections.copy(newList, datas);
Collections.sort(newList, new Comparator<RestaurantData>() {
#Override
public int compare(RestaurantData lhs, RestaurantData rhs) {
return lhs.getDistance() - rhs.getDistance();
}
});
return newList;
}
Another thing to consider is also to create a single instance of the Comparator used in the method, since this implementation will create one instance per call. Not sure if it's worth it though, because it will also be destroyed quite soon since the scope is local.
Here's the documentation for the Collections api
One last thing, the comparator simply needs to return a value less than 0 if the elements are in the right order, bigger than 0 if they're in the wrong order or 0 if they're the same. Therefore it seems to be that it's enough to simply subtract the distances of each restaurant. However, if this isn't the case, please implement the comparator suiting your needs.

Find and print the product of all the entries in array

Okay I have tried to write a simple Java code in BlueJ, that finds and prints the product of all the entries in data such as if data is {1,2,3,4} then the result will be 24.
And my code is below:
public class Product {
public static int[] product(int[] a) {
int [] s = new int[a.length];
for (int i =0; i< a.length; i++)
s[i] = a[i]*a[i];
return s; //the definition of your method...
}
public static void main(String[] args) {
//calling the method to seek if compiles
int[] results = Product.product(new int[] { 1,2,3,4 });
//printing the results
System.out.println(java.util.Arrays.toString(results));
}
}
The above code is giving me the square of each number, which is not what I want to have, somehow I have modify the code that the result will be 24 but I couldn't figure it out, anyone knows how to do it?
First of all, if you are first writing Java it is important to know that variable, function and class names are quite important. Please note that having Product.product() is not a good idea, since the function name is almost the same as the class name. Anyway, regarding your code. Your code is indeed returning the square of your input, what you would want is the following:
public class Product {
public static int getProduct(int[] input) {
int total = 1;
for (int v : input) {
total *= v;
}
return total;
}
}
This will return an integer value with the product of your input array. This also uses a for-each loop instead of a regular for-loop for readability. Also you don't need the index in this case. Good luck with it!
First, your product method needs to return an int rather than an int [].
You need to maintain the product as a variable. You can set it to 1 initially, and then multiply it by each element of the a array in turn; then you just return this value.

Java: How to have one array reference the start of another?

Im trying to make a fun application that will take a sound file and modify it, and create a new sound file.
One of the things I am trying to do is make the sound file twice as long. So I essentially make a new array that goes {2,2,3,3,7,7,8,8} instead of the original {2,3,7,8}. I am using doubles, this is simply an example
I want the original array (samples) to now reference the start of the array I just created (temp) so when the file saves it now save the temp array.
I can increase or decrease the volume of the music file no problem, and save it as such. I omitted that part of the code as it is not pertinent here.
If anyone is kind enough to help me, I also want to know the why behind it
public class Sound {
double[] samples;
//So we only have to declare it once. Reference to an array
public Sound() {
//This constructor should initialize the samples array to be empty
samples = new double[0];
//Initialize an array with nothing because we will be using that to reference the
//location of other arrays
}
public void wavRead(String fileName) {
samples = WavIO.read(fileName);
//Samples was an adress of an array we set to 0. Then we used WavIO to create an aray of doubles, now
//we tell samples to reference this new address over here. Samples has the addsss of the new array
}
public void wavSave(String fileName) {
WavIO.write(fileName, samples);
}
public void lengthen() {
double[] temp = new double[(samples.length *2)];
int t = 0;
for(int i = 0; i < samples.length; i++) {
//Set a variable to increase the temp array by
temp[t] = samples[i];
//Have position 0 of temp = position 0 of soundRaw
t++;
//Increase the position in the temp array by one
temp[t] = samples[i];
//Have position 1 of temp array = position 0 of soundRaw
}
samples[0] = temp;
//Here is where I try and have the samples array reference the start of another array. I tried multiple things, this is simply the last effort I tried
}
And here is the application I am using to test the code
public class App {
public static void main(String[] args) {
Sound s = new Sound();
//We are now calling the other code
s.wavRead("bye8");
//If you want to mess with your own .wav file, replace this name
s.lengthen();
s.wavSave("bye8New");
}
}
Replacing this code line
samples[0] = temp;
with just
samples = temp;
will suffice! :)
Use a DoubleBuffer, it is much easier to do what you want to achieve.
To create a new DoubleBuffer which is... Double... The size and duplicates, you'll then do:
// Important!
origBuf.rewind();
final DoubleBuffer newBuf = DoubleBuffer.allocate(origBuf.remaining() * 2);
double value;
while (origBuf.hasRemaining()) {
value = origBuf.get();
newBuf.put(value).put(value);
}
Then newBuf.array() will return the double[] array "with duplicates".
Also note that a DoubleBuffer, like any XBuffer, allows you to set endianness.
Just use samples=temp; instead of samples[0] = temp;!

Lexicographic quicksort algorithm

My professor gave me a code for the methods to be used in sorting an array of names lexicographically, but I have no idea how what to write inside the main class to show that the program works. I am very new to java, so please if you know how to do this could you write it as simple as possible for me to understand it. Thanks in advance.
This is are the classes
public class quicksort_class {
int[] array1 = new int[11];
public quicksort_class(int[] w)
{
array1 = w;
}
private static void sort(String[] string, int leftlimit, int rightlimit) {
if (rightlimit > leftlimit)
{
int midpoint = partitionstep(string, leftlimit, rightlimit);
sort(string, leftlimit, midpoint - 1);
sort(string, midpoint, rightlimit);
}
}
public static int partitionstep(String[] string, int leftlimit, int rightlimit)
{
String midpoint = string[rightlimit];
int lpointer = leftlimit;
int rpointer = rightlimit;
String temp = "";
while(string[lpointer].compareTo(midpoint) <= 0)
{
lpointer = lpointer ++;
}
while(string[rpointer].compareTo(midpoint) > 0)
{
rpointer = rpointer --;
}
if(lpointer > rpointer)
{
temp = string[lpointer];
string[lpointer] = string[rightlimit];
string[rpointer] = temp;
System.out.println(string);
}
while(lpointer < rpointer)
{
temp = string[lpointer];
string[lpointer] = string[rightlimit];
string[rightlimit] = temp;
}
return lpointer;
}
}
This is the main class (as you can see I have no idea what to write)
package quicksort;
public class Quicksort {
public static void main(String[] args) {
}
}
Write something that sets up an array of strings and calls sort against it, then prints out the results or checks them against a known good result.
Ideally, write something which does this repeatedly, with particular emphasis on checking unusual combinations (already sorted or sorted in reverse, null in the array, same value appearing several times or all values being identical...)
If you want to go beyond that, you need to dig into the code to understand its edge cases and specifically test those, and/or do a "code coverage" analysis (there are tools to help with that) to make sure all parts of the code have been exercised.
Assume the algorithm of sort method is correct:
1. If the main method is within the body of quicksort_class, you can directly call the sort method as sort(arrayToBeSorted, 0 , arrayToBeSorted.length-1). And the arrayToBeSorted should ordered lexicographically after your call. You can check that to confirm.
2. If the main method is in other class, as your main method currently, you need to at least change the private prefix of sort method to public, and call quicksort_class.sort(arrayToBeSorted, 0 , arrayToBeSorted.length-1).
Some tips:
1. Private prefix of method definition means this method can only be called inside current class body.
2. Static prefix of method definition means you should call this method via class name directly, instead of via a instance of class.
By the way, can you provide what the array1 attribute stands for? I don't get why it's there.

Categories