Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Firstly, can you tell me which piece of code is better of selection sort? Then if you know better ways for selection sort, can you please share?
Note: Please inspect the second code closer because it is more complex than it looks.
class SelectionSort {
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
.
class SelectionSort {
public static double[] selectionSort(double[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < i; j++) {
if (array[j] > array[i]) {
double temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
}
}
Both methods will solve your problem but the second one it's clearly and I think it will be faster. Why? Because it has to make less actions to complete the problem: in the first one you have 2 loops (like in the second one), but also it has to make 2 ifs vs 1 if in the second one. I'm not really secure about that but, if the program have to make less actions, it will be faster (just an assumption).
Also, I think it will be faster because in the first one, you through all the j elements, some of them unnecesary (you have to make an extra if), and in the second one you just go through the elements that you need so it is more efficient too.
So, in conclusion, I think the best practice that you have to use it's the second one.
I expect it will helps you a bit!
Performance wise, both are similar, O(n2). The second code is a bit cleaner though.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Kindly help me with the underlying program as I am stuck. I'm a newbie programmer.
import java.util.*;
public class Source
{
static int maxProduct(int arr[]) {
int n = arr.length ;
if (n < 2)
{
System.out.println("NA");
return Integer.MIN_VALUE;
}
int a = arr[0];
int b = arr[1];
for(int i = 0; i<n; i++) {
for (int j = i+1; j<n; j++) {
if (arr[i]*arr[j] > arr[0]*arr[1]) {
a = arr[i];
b = arr[j];
}
}
}
return maxProduct;
}
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int[] arr = new int[size];
for(int i = 0; i < size; i++) {
arr[i] = s.nextInt();
}
int answer = maxProduct(arr);
System.out.print(answer);
}
}
You should change
if (arr[i]*arr[j] > arr[0]*arr[1])
to
if (arr[i]*arr[j] > a * b)
Since arr[0]*arr[1] is just the original max product, so you shouldn't be comparing against it.
Also note that your solution is not as efficient as it can be, since you are using a nested loop, which requires O(n^2) running time.
You can achieve linear (O(n)) running time if you use the fact that the max product is either the product of the two highest positive values or the product of the two lowest negative values. This means that if you find these 4 numbers, which can be done with a single loop, you'll find the max product.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I was trying to attempt a insertion algorithm question. However, I had the following question.
I wanted to nderstand why most solutions online use a nested while loop instead of a nested for loop? I thought it might have to do something with time complexity, however, both have a O(n^2) complexity.
Below I have attached the two different solutions
public class InsertionSort {
// MY method
/*Function to sort array using insertion sort*/
// void sort(int arr[])
// {
// int n = arr.length;
// for (int i = 1; i < n; ++i) {
// if(arr[i] < arr[i-1]){
// for(int j = 0; j < i; j++){
// if(arr[i] < arr[j]){
// int temp = arr[j];
// arr[j] = arr[i];
// arr[i] = temp;
// }
// }
// }
// }
// }
// Online Solution
void sort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
Usually, when developing algorithms, you choose a loop based on this:
If the number of iterations is known, use a for-loop.
If the number of iterations is not known, use a while-loop.
In Java, and other languages, you can implement the same thing using both loops. It doesn't matter if the number of iterations is known. However, it makes sense, it's more readable/logical:
... for a known starting value to a known limit do ...
... while a condition is true do ...
In pseudocode, which is a way to describe an algorithm independently of implementation-details, it's often done just like that (or similar):
for i = 0 to n do
...
while condition do
...
When you look at sort, you can see two loops: the outer for-loop and the inner while-loop.
The outer loop is a for-loop because i and n are known. Value n is known because it's given by the size of the array, which is a constant in this algorithm.
The inner loop is a while-loop because it's not known when the condition will fail, as it depends on an array-access. You don't know the values; if you would, then you could sort the array by hardcoding some swaps.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
public static int keywordsChecker(String essay,String key) {
int count = 1;
String[] k=key.split(",");
for (int i = 0; i < k.length-1; i++) {
if (essay.contains(k[i])) {
count++;
}
}
return count;
}
To take into account that each keyword searched for may occur more than once, and to count such occurrences, you may use this inside your for loop:
int indexOfOccurrence = essay.indexOf(k[i]);
while (indexOfOccurrence > -1) {
count++;
indexOfOccurrence = essay.indexOf(k[i], indexOfOccurrence + 1);
}
There are a couple of other issues in your code: I believe you need to initialize count to 0 (not 1). And to count also the last keyword in key your for loop should be for (int i = 0; i < k.length; i++) (without subtracting 1 from k.length). If you want, using <= would also work: for (int i = 0; i <= k.length-1; i++), but this is non-standard, so I would not recommend it.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I try to print the odd numbers in Java that are inside the array but this algorithm doesn't work ... May someone help me ?
The printing result is that :
"Exception in thread "main" .java.lang.ArrayIndexOutOfBoundsException: 7
at JavaArray.main(JavaArray.java:12)"
Code :
public class JavaArray {
public static void main(String[] args) {
int[] myArray = {1,3,4,5,8,9,10};
int i = 0;
for(i = 0; i < myArray.length; i++); {
if(myArray[i] % 2 == 1) {
System.out.println(myArray[i]);
}
}
}
}
Remove the semi-colon that is terminating your for loop
for (i = 0; i < myArray.length; i++);
^
Because you have placed semicolon after for loop, variable i increments till length of array(here 7). After that loop ends and you are trying to access myarray element through i which is 7 so it is giving out of bound exception.
Besides the extra ; you need to remove, you can consolidate by declaring the int in the loop declaration:
for (int i = 0; i < myArray.length; i++) {
.
.
.
}
Beside #Reimus point , you can also do it like below , sort the array if it's not sorted yet, in your case it is sorted . FYI, Instead of Collections.sort which is above O(N) complexity use a Hash Set.
public static void main(String[] args) {
int[] myArray={1,3,4,5,8,9,10};
Arrays.sort(str);
for (int i = 1; i < myArray.length; i++) {
if (str[i] == str[i - 1]) {
System.out.println("Dupe-num: " + str[i];
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have three for loops, and I wish to turn them into recursive method because I want to do this for any amount of for loops. I searched online, but nobody seems to have exactly what I need, for example this guy turns recursion into for loops
Turning a recursive function into a for loop?
Code:
int x = 3;
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++){
list.add(array[i] + array[j] + array[k]);
}
}
}
Think of a for loop as a little anonymous function that takes the loop index value as a parameter. In order to start the next iteration of the loop, the function can return a call to itself with a new value for the loop index parameter.
Like this:
Object loop(int i, Object data) {
if (i > 0) {
return loop(i - 1, evolve(data));
} else {
return data;
}
}
That's the same as this:
for ( ; i > 0; i--) {
data = evolve(data);
}
In some languages, particularly Scheme, and who knows maybe Java 8 or 9, the compiler is guaranteed to compile a recursive function such as the function loop above just the same as it compiles the for loop above.
In other languages, including the current and past versions of Java, nearly all compilers will make an executable that builds a big call stack. When the call stack is large it may even overflow the permitted size and crash the program.
Haters aside, let's do this! [1]
Given:
int x = 3;
for (int i = 0; i < x; i++) {
for (int j = 0; j < x; j++) {
for (int k = 0; k < x; k++){
list.add(array[i] + array[j] + array[k]);
}
}
}
Let's consider that each loop is it's own recursive function - as this makes the recurrence cases much easier! This is also the only "non-thinking" method I know of to turn the loops into recursion. The recursive depth will be limited to 3*x => i+j+k so it's "fairly safe" for a smallish[2] x.
In Java it requires a separate method for each loop to encode this structure. (In a language with higher-order functions these three functions might be abstractly combined .. but not in Java [7].)
void loopI(int i) {
if (i < x) {
loopJ(0); // "start j loop"
loopI(i++); // "next i loop" / recurrence case
}
// "end loop" / base case
}
void loopJ(int j) {
if (j < x) {
loopK(0);
loopJ(j++);
}
}
void loopK(int k) {
if (k < x) {
list.add(array[i] + array[j] + array[k]);
loopK(k++);
}
}
// do it!
loopI(0);
All of these could be combined into a single recursive function, but that makes handling the recurrence cases a bit tougher as "thinking" and additional conditionals (or mod expressions, perhaps) are required to advance the state.
Here is an example of a combined recursive function (this is incorrect when x is 0). Unlike the three method approach above, the stack depth will grow to x^3 => i*j*k. This will easily kill Java's recursion limits - even for smallish values of x- as Java [7] doesn't have tail-call optimization.
void loop(int i, int j, int k) {
list.add(array[i] + array[j] + array[k]);
// advance states
k++;
if (k == x) { k = 0; j++; }
if (j == x) { j = 0; i++; }
if (i == x) { i = 0; }
// terminate on all wrap-around
if (i == 0 && j == 0 && k == 0) { return; }
// recurse
loop(i, j, k);
}
[1] YMMV, for theoretical purposes only - I love recursion, but it's not suited for this case in Java.
[2] For some value of "smallish". See how deep your stack can go!