I am very interested in how to sort 5 items using only 7 comparisons.
I think I understand the theory how to do it but unfortunately I'm not able to write it as a code.
Here I found an example in LISP
I really tried to understand it but it seems to me be not working. For example on the numbers 5,4,3,2,1.
Could anybody please give me an example code, but not in LISP? I prefer Java or C/C++. It would really help me in school.
Thank you in advance
P.S. Sorry for my english
Edit:
Here I add some piece of code I wrote in Java.
Variables a,b,c,d,e are there only for my better orientation in code.
I'm able to write specific code for specific input items, that's no problem.
But I can't write general code.
public static void sort(int p[]) {
int a = 0;
int b = 1;
int c = 2;
int d = 3;
int e = 4;
if (p[a] > p[b]) {
swap(p,a,b);
}
if (p[c] > p[d]){
swap(p,c,d);
}
if (p[b] > p[d]){
swap(p,b,d);
}
if (p[e] < p[b]) {
if (p[e] < p[a]) {
swap(p,a,e);
swap(p,d,e);
//swap(p,b,d);//BLBE
}else{
swap(p,b,e);
swap(p,d,e);
}
}else {
if (p[e] < p[d]) {
swap(p,d,e);
}
}
if (p[c] < p[b]) {
if (p[c] < p[a]) {
swap(p,a,c);
swap(p,b,c);
}else
{
swap(p,c,b);
}
}else {
if (p[c] > p[d]) {
swap(p,d,c);
}
}
}
Writing a general comparison-based sorting algorithm takes O(n lg n) comparisons. If I'm not mistaken, then all O(n lg n) sorting algorithms will sort 5 items in about 7 comparisons. Mergesort, Heapsort and Quicksort if you're lucky.
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 last year.
Improve this question
LeetCode 485
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Example 1:
Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
---------Solution:-------
public int findMaxConsecutiveOnes(int[] nums) {
int maxConsSize = Integer.MIN_VALUE;
int i = -1, j=-1, k=0;
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
return maxConsSize;
}
Warning: This is not direct answer (for this "do my homework" question)
You should use (or learn to use) debugger in your IDE (trust me, IDE, e.g. Eclipse will help you a lot in your beginnings).
The easiest (I'm not saying smartest) way, how to know what the program is doing (when you need to know, like in this case) is to add some print statements, e.g. add System.out.println("k=" + k) into your program (in a while loop).
You might want to watch this youtube video.
You have an infinity loop. Try run this:
public class Test {
public static void main(String[] args) {
int maxConsSize = Integer.MIN_VALUE;
int[] nums = {1,1,0,1,1,1};
int i = -1, j=-1, k=0;
System.out.println(nums.length);
while(k<nums.length){
while(k<nums.length && nums[k] == 1){
k++;
i++;
System.out.println("k = " + k);
}
if(nums[k] == 0){
maxConsSize = Math.max(maxConsSize,i-j);
j = i;
}
}
maxConsSize = Math.max(maxConsSize,i-j);
System.out.println(maxConsSize);
}
}
Output:
6
k = 1
k = 2
After reading the first 0 you are in infinite loop. You have made this task very complicated :)
It's probably not the best solution, but it should be faster
public int findMaxConsecutiveOnes(int[] nums) {
int maxCons = 0;
int currentCons = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
if (currentCons > maxCons) {
maxCons = currentCons;
}
currentCons = 0;
} else {
currentCons++;
}
}
if (currentCons > maxCons) {
maxCons = currentCons;
}
return maxCons;
}
}
There are two basic forms of loops:
for-each, for-i or sometimes called ranged for
Use that for a countable number of iterations.
For example having an array or collection to loop through.
while and do-while (like until-loops in other programming languages)
Use that for something that has a dynamic exit-condition. Bears the risk for infinite-loops!
Your issue: infinite loop
You used the second form of a while for a typical use-case of the first. When iterating over an array, you would be better to use any kind of for loop.
The second bears always the risk of infinite-loops, without having a proper exit-condition, or when the exit-condition is not fulfilled (logical bug). The first is risk-free in that regard.
Recommendation to solve
Would recommend to start with a for-i here:
// called for-i because the first iterator-variable is usually i
for(int i=0; i < nums.length, i++) {
// do something with num[i]
System.out.println(num[i]):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no counting, etc. inside the loop-body
Even simpler and idiomatic pattern is actually to use a for each:
for(int n : nums) {
// do something with n
System.out.println(n):
}
because:
it is safer, no risk of infinite-loop
the iterations can be recognized from the first line (better readability)
no index required, suitable for arrays or lists
no counting at all
See also:
Java For Loop, For-Each Loop, While, Do-While Loop (ULTIMATE GUIDE), an in-depth tutorial covering all about loops in Java, including concepts, terminology, examples, risks
so I got a project for a computer science module, and they ask us to perform ITERATIVE quick and merge sorts, so I wrote an algorithm, but I am unsure if it is iterative or recursive.
Any feedback would be greatly appreciated, thanks in advance!
Here is the algorithm (it works, just need to know if it is iterative or not)
public static void quickSort(ArrayList<school> x){
if(x.isEmpty()){
return ;
}
ArrayList<school> smaller = new ArrayList<>();
ArrayList<school> greater = new ArrayList<>();
school pivot = x.get(0); // pivot value
int i; // incremental counter
school j; // looping value
for( i=1; i < x.size();i++){
j = x.get(i);
if( j.getName().compareTo(pivot.getName()) < 0 ){
smaller.add(j);
}else{
greater.add(j);
}
}
quickSort(smaller);
quickSort(greater);
x.clear();
x.addAll(smaller);
x.add(pivot);
x.addAll(greater);
}
The quickSort function is called from within itself, therefore this is recursive.
For example I have this array:
int[] a = {1,1,1,1,5,5,1,1,1};
//output: 4 2 3
In other words, it will print the sequences of the same number.
I have already tried this:
int doubles_count_while (int a[][], int n, int cestatic) {
int result = 1;
while (result < n && a[result - 1][cestatic] == a[result][cestatic]) {
result++;
}
return result;
}
int doubles_groups(int a[][], int n, int cestatic, int b[]) {
int result = 0;
int i = 0;
while (i < n) {
int z = doubles_count_while(a, n-i, a[i][cestatic]);
b[result++] = z; i += z;
}
return result;
}
When posting code, please post it as an MCVE so that we can actually run it. You should also tell us what you expect this code to do and what it does instead. Try to narrow it down to a single line of code that's not doing what you expect it to do.
This is a pretty broad question, but I'll try to help in a general sense. You need to take a step back and forget about the code for a second. Write down the steps you would follow, without a computer, if somebody handed you a stack of index cards with numbers written on them and asked you to group them. How exactly would you do that?
Pretend you have a really dumb friend who has no idea how to group the cards. You should be able to hand your instructions to that friend and have them follow them to group the cards without any help from you. Remember how dumb this friend is, so make sure your instructions are as small as possible.
When you have those instructions written out, that's an algorithm that you can start thinking about implementing with code. Trying to dive into the code without a clear idea of what you want it to do is just going to give you a ton of headaches. Good luck.
I am trying to implement an QuickSort algorithm on an ArrayList. However, I am getting a
Exception in thread "main" java.lang.StackOverflowError
at sorting.QuickSort.quickSort(QuickSort.java:25)
at sorting.QuickSort.quickSort(QuickSort.java:36)
at sorting.QuickSort.quickSort(QuickSort.java:36)
at sorting.QuickSort.quickSort(QuickSort.java:36)
at sorting.QuickSort.quickSort(QuickSort.java:36)
...
I am not sure as to why is there an overflow. Below is my implementation:
public static void quickSort(ArrayList<Integer> al, int fromIdx, int toIdx) {
int pivot, pivotIdx;
if (fromIdx < toIdx) {
pivot = al.get(fromIdx);
pivotIdx = fromIdx;
for (int i = 0; i != (fromIdx + 1); i++) {
if (al.get(i) <= pivot) {
pivotIdx += 1;
swap(al, pivotIdx, i);
}
}
swap(al, fromIdx, pivotIdx);
quickSort(al, fromIdx, pivotIdx - 1);
quickSort(al, pivotIdx + 1, toIdx);
}
}
public static void swap(ArrayList<Integer> al, int xIdx, int yIdx) {
Integer temp = al.get(xIdx);
al.set(xIdx, al.get(yIdx));
al.set(yIdx, temp);
}
If you're trying to sort the chunk of the array from fromIdx to toIdx, you should never look at element 0 unless it is in that chunk. But your implementation does.
Your indexing trick in the middle is also kind of..odd. I highly recommend that you do the exercise of cutting out little pieces of paper for the array, and writing tracking information on a sheet of paper so that you can trace through the algorithm. If when you physically do it, you see it not make sense, then it doesn't make sense in the computer either. And the act of holding physical pieces of paper may seem silly, but is of great help in visualizing exactly what you are doing. (The more precisely you can visualize what your code actually does, the more likely you are to be able to figure out if it is doing something wrong.)
I am trying to write a method to remove a chromosome from my population. The method I have written is below. I am getting an out of bounds error when I run the code. Population is constructed with an ArrayList. The getChromosomeFitness method returns an int value score. Can someone spot my error?
void removeWorst()
{
int worst = population.get(0).getChromosomeFitness();
int temp = 0;
for(int i = 1; i < population.size(); i++)
{
if (population.get(i).getChromosomeFitness() < population.get(worst).getChromosomeFitness())
{
worst = population.get(i).getChromosomeFitness();
temp = i;
}
}
Chromosome x = population.get(temp);
population.remove(x);
}
You should probably change
if (population.get(i).getChromosomeFitness() < population.get(worst).getChromosomeFitness())
to
if (population.get(i).getChromosomeFitness() < worst)
You don't assure that in this line population has an element with the index 0:
int worst= population.get(0).getChromosomeFitness();
Try to add this to your method:
void removeWorst() {
if (population.isEmpty()) {
return;
}
...
There are several potential problems in your code:
int worst= population.get(0).getChromosomeFitness();
you need to make sure that population.isEmpty() is false
population.get(worst).getChromosomeFitness()
same thing, you need to make sure that (worst >= 0 && worst < population.size()).
The issue seems that you are getting the actual fitness rather than the object itself. The issue is with this line: int worst= population.get(0).getChromosomeFitness();. This is returning an integer value which is not related to the List's dimensions, as you said, it is the fitness of the chromozome, which could be well over the size of the list.
This should solve the problem:
void removeWorst()
{
int temp=0;
for(int i=1; i <population.size();i++)
{
if (population.get(i).getChromosomeFitness() < population.get(temp).getChromosomeFitness())
{
temp=i;
}
}
Chromosome x= population.get(temp);
population.remove(x);
}
That being said, a probably neater way of doing this would be to use a custom comparator to sort the list and then simply remove the last element.
Make sure population has something in it before trying to remove something from it?