sorting arrays only sorts a few - java

I`ve been trying to bubble sort an array in java for some time now, but every time it just does a few and then it follows the array list.
public void mysort() {
Random randomNumbers = new Random();
int randomArray[] = new int[20];
for (int j = 0; j <= 19; j++) {
randomArray[j] = randomNumbers.nextInt(200 + 1);
for (int k = 1; k < 20; k++) {
if (randomArray[k - 1] < randomArray[k]) {
int hjelp = randomArray[k - 1];
randomArray[k - 1] = randomArray[k];
randomArray[k] = hjelp;
}
}
}
for (int i = 0; i <= 19; i++) {
System.out.println(randomArray[i]);
}
}
How do I make my bubble sort work properly?

You should populate the array first, and THEN call the sort. You're "sorting" the array 20 times, while it's still incomplete.
public void mysort() {
Random randomNumbers = new Random();
int randomArray[] = new int[20];
for (int j = 0; j < randomArray.length; j++) {
randomArray[j] = randomNumbers.nextInt(200) + 1;
}
for (int i = 0; i < randomArray.length; i++) {
for (int k = 1; k < randomArray.length; k++) {
if (randomArray[k - 1] < randomArray[k]) {
int hjelp = randomArray[k - 1];
randomArray[k - 1] = randomArray[k];
randomArray[k] = hjelp;
}
}
}
for (int i = 0; i < randomArray.length; i++) {
System.out.println(randomArray[i]);
}
}

You need to populate array first.
You are trying to populate and sort at the same time.
Populate :
for (int j = 0; j <= 19; j++ ){
randomArray[j] = randomNumbers.nextInt(200+1);
}
Sort :
BubleSort();

You code should have been like this :
Random randomNumbers = new Random();
int randomArray[] = new int[20];
for (int j = 0; j <= 19; j++) {
randomArray[j] = randomNumbers.nextInt(200 + 1);
}
for(int j=0;j<20;j++) {
for (int k = 1; k < 20; k++) {
if (randomArray[k - 1] < randomArray[k]) {
int hjelp = randomArray[k - 1];
randomArray[k - 1] = randomArray[k];
randomArray[k] = hjelp;
}
}
}
for (int i = 0; i <= 19; i++) {
System.out.println(randomArray[i]);
}
Note you are doing this in descending order. if you want to do it in ascending order change
if (randomArray[k - 1] < randomArray[k])
to
if (randomArray[k - 1] > randomArray[k])

Related

Exchange values of two arrays, make another array without repeats and sort from highest to lowest

I know I have to do it with a while or do while loop, but I can't get it working. I also tried with a for loop, but it always gives me an error because I don't know the exact length of the vectors because they are random.
int a = (int)(Math.random() * 3 + 1);
int b = (int)(Math.random() * 3 + 1);
int c = a + b;
int[] arrA = new int[a];
int[] arrB = new int[b];
int[] arrC = new int[c];
for (int i = 0; i < a; i ++) {
arrA[i] = (int)(Math.random() * 10 + 1);
for (int j = 0; j < b; j ++) {
arrB[j] = (int)(Math.random() * 10 + 1);
}
}
Arrays.sort(arrA);
Arrays.sort(arrB);
System.out.println(Arrays.toString(arrA));
System.out.println(Arrays.toString(arrB));
System.out.println(Arrays.toString(arrC));
Take values from arrays arrA and arrB, and insert to arrC
int index = arrA.length;
for (int i = 0; i < arrA.length; i++) {
arrC[i] = arrA[i];
}
for (int i = 0; i < arrB.length; i++) {
arrC[i + index] = arrB[i];
}
Sort arrC
Arrays.sort(arrC);
Reverse the order and store in arrD
for(int l = 0; l < arrC.length; l++) {
arrD[l] = arrC[arrC.length - (l+1)];
}
Remove duplicate (simplified)
Set<Integer> remove=new LinkedHashSet<Integer>();
for(int i = 0;i < arrD.length;i++){
remove.add(arrD[i]);
}
Remove duplicate (usual)
int index2 = 0;
for (int i = 0; i < arrD.length; i++) {
for (int k = 0; k < arrD.length; k++) {
if (arrD[i] != arrD[k]) {
arrE[index2] = arrD[i];
index2++;
}
}
}

Levenshtein distance in java outputting the wrong number

For my university assignment in java I have been asked to provide "extra analytics functions" I decided to use Levenshtein distance but I have an issue where the number outputted to the console is one less than the actual answer. So the distance between "cat" and "hat" should be 1 but it's displaying as 0
public class Levenshtein {
public Levenshtein(String first, String second) {
char [] s = first.toCharArray();
char [] t = second .toCharArray();
int Subcost = 0;
int[][] array = new int[first.length()][second.length()];
for (int i = 0; i < array[0].length; i++)
{
array[0][i] = i;
}
for (int j = 0; j < array.length; j++)
{
array [j][0]= j;
}
for (int i = 1; i < second.length(); i++)
{
for (int j = 1; j < first.length(); j++)
{
if (s[j] == t [i])
{
Subcost = 0;
}
else
{
Subcost = 1;
}
array [j][i] = Math.min(array [j-1][i] +1,
Math.min(array [j][i-1] +1,
array [j-1][i-1] + Subcost) );
}
}
UI.output("The Levenshtein distance is -> " + array[first.length()-1][second.length()-1]);
}
}
Apparently you're using the following algorithm:
https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_full_matrix
I think you were not too accurate with indices. I'm not sure where exactly the problem is, but here is a working version:
public int calculateLevenshteinDistance(String first, String second) {
char[] s = first.toCharArray();
char[] t = second.toCharArray();
int substitutionCost = 0;
int m = first.length();
int n = second.length();
int[][] array = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
array[i][0] = i;
}
for (int j = 1; j <= n; j++) {
array[0][j] = j;
}
for (int j = 1; j <= n; j++) {
for (int i = 1; i <= m; i++) {
if (s[i - 1] == t[j - 1]) {
substitutionCost = 0;
} else {
substitutionCost = 1;
}
int deletion = array[i - 1][j] + 1;
int insertion = array[i][j - 1] + 1;
int substitution = array[i - 1][j - 1] + substitutionCost;
int cost = Math.min(
deletion,
Math.min(
insertion,
substitution));
array[i][j] = cost;
}
}
return array[m][n];
}

Sort array in descending order and collect the changes of main array in new array

public static int[] sortByScores(double[] scores){
double temp;
int i,j;
int[] scoreIndex = new int[3];
for (i = 0; i <= scores.length; i++)
for (j = i+1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
scoreIndex[i] = j;
scoreIndex[j] = i;
}
}
return scoreIndex;
}
This method sort the "scores" array in descending order and store which index key is changed from the array in "scoreIndex" array.
This method doesn't work if I enter 1,3,2,4
Is they any better way to store the index key changes log?
Example if 1 enter:
1
2
4
3
Sorted will be:
4
3
2
1
And sortIndex should be:
Key Value
0 3
1 2
2 0
3 1
You can actually get the array containing the proper ordering of the elements at certain indices without sorting this array, for example, by doing this:
for(int i = 0; i < scores.length; i++) {
for(int j = i; j < scores.length; j++) {
if(scores[scoreIndex[j]] > scores[scoreIndex[i]]) {
int temp = scoreIndex[j];
scoreIndex[j] = scoreIndex[i];
scoreIndex[i] = temp;
}
}
}
In short, at the beginning of this method we are creating an array which contains the current order of indices in your scores[] array, this is 0, 1, ..., scores.length-1. Then, we perform an operation similar to standard sorting but not in terms of the scores[] array, but in terms of the scoreIndex[] array.
Once we have this array sorted, we can create another array and and place its elements at the appropriate position by:
double[] copy = new double[scores.length];
for(int k = 0; k < scores.length; k++) {
copy[k] = scores[k];
}
for(int n = 0; n < scores.length; n++) {
scores[n] = copy[scoreIndex[n]];
System.out.println(scores[n]);
}
So, to put it together:
public static int[] sort(double[] scores) {
int[] scoreIndex = new int[scores.length];
for(int i = 0; i < scores.length; i++) {
scoreIndex[i] = i;
}
for(int i = 0; i < scores.length; i++) {
for(int j = i; j < scores.length; j++) {
if(scores[scoreIndex[j]] > scores[scoreIndex[i]]) {
int temp = scoreIndex[j];
scoreIndex[j] = scoreIndex[i];
scoreIndex[i] = temp;
}
}
}
double[] copy = new double[scores.length];
for(int k = 0; k < scores.length; k++) {
copy[k] = scores[k];
}
for(int n = 0; n < scores.length; n++) {
scores[n] = copy[scoreIndex[n]];
System.out.println(scores[n]);
}
return scoreIndex;
}
First, you should declare scoreIndex as:
int[] scoreIndex = new int[scores.length];
And, in every outer loop, you find the max element, set it as scores[i], at the same time, set scoreIndex[indexOfMaxElement] = i. To achieve this, you also need a copy of the origial array.
Here is the complete code:
public class Main {
public static void main(String[] args) {
double[] array = new double[] {1, 2, 4, 3};
int[] result = sortByScores(array);
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
public static int[] sortByScores(double[] scores){
int[] scoreIndex = new int[scores.length];
double[] copy = new double[scores.length];
boolean[] records = new boolean[scores.length];
// copy
for (int i = 0; i < scores.length; i++) {
copy[i] = scores[i];
}
for (int i = 0; i < scores.length; i++) {
// find the max element
for (int j = i + 1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
double temp = scores[i];
scores[i] = scores[j];
scores[j] = temp;
}
}
// set the max element's index
for (int k = 0; k < copy.length; k++) {
if (copy[k] == scores[i] && !records[k]) {
scoreIndex[k] = i;
records[k] = true;
break;
}
}
}
return scoreIndex;
}
}
My one worked too but #user6690200 your one is way better.
public static int[] sortByScores(double[] scores){
double temp,temp2;
int i,j;
int[] scoreIndex = new int[3];
double[] scoreBackup = new double[scores.length];
double[] scoreBackup2 = new double[scores.length];
// Generating unique score, beacuse student can have same score
for(i=0;i<scores.length;i++)
scoreBackup[i] = scores[i]*(i+1);
for(i=0;i<scores.length;i++)
scoreBackup2[i] = scores[i]*(i+1);
for (i = 0; i < scores.length; i++) {
for (j = i+1; j < scores.length; j++) {
if (scores[i] < scores[j]) {
temp = scores[i];
temp2 = scoreBackup2[i];
scores[i] = scores[j];
scoreBackup2[i] = scoreBackup2[j];
scores[j] = temp;
scoreBackup2[j] = temp2;
}
}
}
for(i = 0; i<scores.length;i++)
for(j=0;j<scores.length;j++)
if(scoreBackup[i] == scoreBackup2[j])
scoreIndex[i] = j;
return scoreIndex;
}

Java - Selection Sort - only switching once

So the first switch definitely occurs between the lowest value 3, and 5, but it doesn't keep going after that. This makes me think there is something wrong with one of the for loops?
public class SelectionSort
{
public static void main (String[] args)
{
int [] list;
list = new int[5];
list[0] = 4;
list[1] = 5;
list[2] = 12;
list[3] = 9;
list[4] = 3;
for (int i = 0; i < list.length-1; ++i) {
int index = i;
for (int j = 1; j < list.length; ++j) {
if (list[j] < list[index]) {
int temp = list[j];
list[j] = list[index];
list[index] = temp;
}
}
}
for (int k = 0; k < list.length; ++k) {
System.out.print(list[k] + ", ");
}
}
}
Short versión:
for (int i = 0; i < list.length-1; i++)
for (int j = i+1; j < list.length; j++)
if (list[j] < list[i]) {
int temp = list[j];
list[j] = list[i];
list[i] = temp;
}
for (int k = 0; k < list.length; k++) {
System.out.print(list[k] + ", ");
}
after if (list[j] < list[index]) {, you have to update index if boolean statement gets satisfied so you need to index = j and do the swap after
see follwing :
public class MySelectionSort {
public static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
for (int i = 0; i < list.length; ++i) {
int index = i;
for (int j = i + 1; j < list.length; ++j) {
if (list[j] < list[index]) {
index = j; }}
if (index != i) {
int temp = list[i];
list[i] = list[index];
list[index] = i; }}
To cut down on the number of swaps, the loop on j should only be looking the best item to swap with item i. There should be at most one swap for each value of i. (That's what makes it a Selection sort. If you do multiple swaps for each i, you might as well be doing Bubble Sort.
But that's for efficiency. The reason your code isn't working is that you start the loop on j at j = 1 instead of j = i + 1.

find Prime numbers up to X - complexity

this algorithm is need to make an array with size X and then each number which isnt prime toput zero in his index.. can someone please tell me what is the complexity? and why?
// x is the number we want all the primes below him
int[] p = new int[x + 1];
// Initializes the array.
for (int i = 2; i < p.length; i++) {
p[i] = i;
}
// "Erases" the composite (non-prime) numbers.
for (int i = 2; i <= Math.sqrt(x); i++) {
for (int j = i * 2; j < p.length; j += i) {
p[j] = 0;
}
}
is the complexity is O(x*sqrt(x))?
If you are using the following code, the time complexity is O(x √x).
int[] p = new int[x];
for (int i = 0; i < p.length; i++) {
p[i] = i+1;
}
for (int i = 4; i <= p.length; i++) {
for(int j = 2; j <= Math.sqrt(i) ; j += 1) {
if(i%j==0) {
p[i-1] = 0;
}
}
}

Categories

Resources