So what I have to do is insert certain values from one array to another one directly sorted without having to sort them later using BubbleSort or QuickSort or any other method. I can't think of a way to do this... I have to insert them from the biggest value to the smallest one. Here's what I have until now:
void palindroame (int x[100], int y[100]) {
int i=0, j, k=0, aux;
while (x[i]!=0) {
k++; i++;
}
i=0;
for (i=0; i<=k-1; i++) y[i]=0;
for (i=0; i<=k-1; i++) {
if (palindrom(x[i])!=0 && palindrom(x[i+1])!=0)
if (x[i]<x[i+1]) {
aux=x[i+1]; x[i+1]=x[i]; x[i]=aux;
}
} //wrong
for (i=0; i<=k-1; i++) {
if (palindrom(x[i])) y[i]=x[i];
} //wrong
}
Thanks in advance!
The algorithm you need is selection sort, you can use this to sort and copy at the same time.
You can have a look at priority queues:
http://www.cplusplus.com/reference/queue/priority_queue/
Heres an example of a selection sort i have done recently (in which a is a vector)
should give you enough to go on hope it helps, ask questions if u like
for (unsigned int i = 0; i < a.size()-1; i++)
{
int min = i;
for(unsigned int j = i +1; j < a.size(); j++)
{
// If new minimum is found then stores this as the new minimum
if(a[j] < a[min])
{
min = j;
}
}
// Stores the values in the array in ascending order
if (min != i)
{
int temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
// Returns the array in ascending order
return a;
Edit: just to clarify this is working on a vector that already has values in it in case that wasnt clear but example with code comments i think is enough to help you IMO
Related
I am trying to make a program that sorts an array without using the sort function (that won't work with objects or structs). I have made the greater than one work, but the less than one keeps changing the greatest element in the array to a one and sorting it wrong, and when used with the greater than function, the first element is turned into a large number. Can someone please help me fix this or is it my compiler.
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++) {
for(int i = 0; i < size; i++) {
if(array[i] > array[i+1]){
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
}
}
You are not looping correctly. Looks like you are trying bubble sort which is:
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++)
for(int i = k+1; i < size; i++)
if(array[i] < array[k]){
int temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
void min_sort(int array[], const unsigned int size)
{
for(int i=0;i<size-1;i++)
{
for(int j=0;j<size-1-i;j++)
{
if(array[j]>array[j+1])
{
swap(array[j] , array[j+1]);
}
}
}
}
I see that you are trying to implement the bubble sort algorithm. I have posted the code for bubble sort here. In bubble sort you basically compare the element at an index j and the element next to it at index j+1. If array[j] is greater than array[j+1] , you swap them using the swap() function or by using the temp method. The outer loop will run size - 1 times , and the inner loop will run size - 1 - i times because the last element will already be in place.
For Example we have an array of size 4 with elements such as :
array[i] = [100,90,8,10]
The bubble sort will sort it in the following steps :
90,100,8,10
90,8,100,10
90,8,10,100
8,90,10,100
8,10,90,100
8,10,90,100
See, the use of size-1-i . You can see the nested loop runs less number of times in each iteration of the outer loop.
There is only one mistake that your 2nd loop condition should be: i < size -1.
So it should be:
for (int i = 0; i < size -1; i++)
Your attempt at bubble sort is basically correct, you just have an out of bounds issue with your inner loop. During the inner loop's last run, i == size - 1, therefore i + 1 is equal to size, thus data[i+1] is out of range. Simply change the condition of your for to be i < size - 1.
Working example: https://godbolt.org/z/e5ohWPfTz
#include<bits/stdc++.h>
int main()
{
int n;
std::cin>>n;
char st[n];
getchar();
for (int i=0; i<n; ++i)
st[i]=getchar();
std::multiset<char> s;
int pos1=0,pos2=n-1;
for (char c:st) s.insert(c);
for (int i=0; i<n; ++i) {
if (s.count(st[i])==1) {
pos1=i;
break;
} else s.erase(s.find(st[i]));
}
for (int i=n-1; i>=0; --i) {
if (s.count(st[i])==1) {
pos2=i;
break;
} else s.erase(s.find(st[i]));
}
std::cout<<pos2-pos1+1;
}
I have just summit this code to CodeForces system, and it fail the TL (2s), i dont know why, because n constrain is 10^5. And my code work with O(nlogn). Can u guys help me? Thanks <3<3. Link of problem here : http://codeforces.com/problemset/problem/701/C
Indeed, your algorithm is O(nlogn) but this is not a garantee to not exceed a time limit. Remember that the multiplication constant for a big-O complexity may be too big to keep it under a certain time limit.
You are using a multiset only for keeping a count for each type of Pokemon. You lose much time to erase from that multiset and count again from it. You can do much faster than the multiset:
By using a map to keep the count for each type and to update it
Better yet, since pokemon types are encoded in single chars, you can use an array of 256 elements to keep track of the count. This way you can avoid the "log(n)" complexity of multiset (and map). Here's a refactored version of your code that should run much faster, and moreover it runs in O(n).
int main()
{
int n;
std::cin >> n;
std::vector<char> st(n);
std::array<int, 256> count; // we could also use a map if we had a bigger set of types...
// the way you read the input can also be speeded-up,
// but I want to focus on speeding up the algorithm
getchar();
for (int i=0; i<n; ++i) {
st[i]=getchar(); ++count[st[i]];
}
int pos1=0,pos2=n-1;
for (int i=0; i < n; ++i) {
if (count[st[i]] == 1) {
pos1 = i;
break;
} else --count[st[i]];
}
for (int i=n-1; i>=0; --i) {
if (s.count(st[i])==1) {
pos2=i;
break;
} else --count[st[i]];
}
std::cout<<pos2-pos1+1;
}
I have problem understanding the selection sort algorithm where integers are rearranged from lowest to highest value. Here is the code:
#include<iostream>
using namespace std;
void SelectionSort(int A[], int n)
{
for (int i = 0; i < n-1; i++)
{
int iMin = i;
for (int j = i+1; j < n; j++)
{
if (A[j] < A[iMin])
iMin = j;
}
int temp = A[i];
A[i] = A[iMin];
A[iMin] = temp;
}
}
int main()
{
int A[] = {2, 4, 3, 5, 1};
SelectionSort(A, 5);
for (int i = 0; i < 5; i++)
cout<<A[i]<<" ";
}
Can someone help me by explaining in details how the integers are rearranged and give some comments to each line? Maybe its easy but I am dumb in programming. :(
In coding writing comments in each line doesn't usually make sense, because the line itself usually states very clearly what it does. What matters though is the structure.
What your algorithm does is go trough the list from beginning to end (the first for), and for each integer in the list, it swaps the current integer with the smallest integer in the rest of the list.
But to do this, it needs to find it first. This is where the second for comes in. It walks trough the rest of the list (because it starts at i and not at 0), and remembers the position (iMin) of the smallest integer.
I want somehow sort an array, so that it looks like -
a[0]>=a[1]<=a[2]>=a[3]<=a[4]
I don't know where to start.
Any suggestion would be appreciated!
Sort the entire array (Choose any sort algorithm you wish to). Then take each pair from the beginning and swap the elements in the pair
2,4,1,5,6,3,7,9,8,10
Sorted to : 1,2,3,4,5,6,7,8,9,10
Pair and swap : (2,1),(4,3),(6,5),(8,7),(10,9)
result : 2,1,4,3,6,5,8,7,10,9
Here's the code, obviously you can alter the array length and numbers to meet your specifications.
#include <iostream>
#include <algorithm>
using namespace std;
void special_Sort(int *array, int size){
//doesn't return a value, changes the values inside the array
int temp;
//for swapping purposes
sort(array, array+size);
//sorts the array in ascending order
for(int i=0; i<size; i=i+2){
temp=array[i];
array[i]=array[i+1];
array[i+1]=temp;
}
//array is now sorted
}
int main(){
// array declaration, call the function, etc...
int array[10]={2,4,1,5,6,3,7,9,8,10};
int *pointer;
pointer=&array[0];
special_Sort(pointer, 10);
// if you want to print the result
// for(int i =0; i<10; i++)
// cout<<array[i]<<" ";
return 0;
}
I'm assuming here that the relations are inclusive (in the sense that they continue to the end of the line - a[0]>=max(a[1],a[2],...), and a[1]<=min(a[2],a[3],..) and so on). Otherwise this isn't uniquely defined, as {5,4,3,2,1} can get sorted for example into {5,1,4,3,2} or {3,2,5,1,4}.
So, assuming this is the case, it's easily solved by sorting the entire array in descending order, then just interleave them -
a[0], a[n-1], a[1], a[n-2], ...
and so on. Just loop with two indices, one starting from the beginning and one from the end, or use something like this -
for (i=0; i<n/2; i++) {
result[i*2] = sorted[i];
result[i*2+1] = sorted[n-i];
}
if (n%2)
result[n-1] = sorted[n/2]
If you are only sorting it in a way that you want values to rise and fall arbitrarily, you can achieve this by checking values in your array and swapping elements if they do not satisfy the constraints of your sort.
Don't have a compiler on me at the moment and you'd have to implement the swap but something like this could work:
for(i=0; i < a.length(); i++){
//If index is even
if(i%2 == 0){
if(a[i] < a[i+1]){
swap(a[i], a[i+1]);
}
} else { ///If index is odd
if(a[i]>a[i+1]){
swap(a[i], a[i+1];
}
}
}
I don't disagree with the other answers posted here so you will have to find what you need depending on the relation of the even and odd indexed elements.
Steps taken:
1) generate some random array
2) sort array
3) switch elements as needed with alternate <=, >= comparisons
Here's the code that does that: (disregard the random generator, its just an easy way to generate an array)
#define sizeArr 50
int main(void)
{
int array[sizeArr];
int i, temp;
for(i=0;i<sizeArr;i++)
{
array[i]=randomGenerator(1, 1000);
Sleep(2);//force clock tick for new srand() to be effective in rand() generator
}
//sort array
qsort(array, sizeArr, sizeof(int), cmpfunc);
//pick the first non repeat 90th percent and print
for(i=0;i<sizeArr-1;i++)
{
if(i%2==0)//alternate between >= && <=
{
if(array[i+1] >= array[i])
{
temp = array[i+1];
array[i+1]=array[i];
array[i]=temp;
}
}
else
{
if(array[i+1] <= array[i])
{
temp = array[i+1];
array[i+1]=array[i];
array[i]=temp;
}
}
}
getchar();
return 0;
}
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int randomGenerator(int min, int max)
{
int random=0, trying=0;
trying = 1;
srand(clock());
while(trying)
{
random = (rand()/32767.0)*(max+1);
(random >= min) ? (trying = 0) : (trying = 1);
}
return random;
}
I am a beginner in C++. I typed a simple code to sort an integer array, but I couldn't figure out how to handle same elements like if I enter 1,12,3,5,11,3
output is given as 1,3,3,5,11,12 but I want the output to be 1,3,5,11,12.
What should I add further in the loop I've coded?
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(array[i]>array[j])
{
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
If you really want to write it by yourself, do as they told you in comments.
If you just want to have a sorted list without duplicates, use std::set and insert all your numbers inside. You will get a sorted, unique list of ints.
It may be easier for you to understand this solution:
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(array[i]>array[j])
{
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
cout<<array[0];
for(int i=1; i<len; ++i)
{
if(array[i] != array[i-1])
{
cout<<array[i];
}
}
Normal way :
Remove the duplicates from the array that you've sorted
int *start = array;
int *end = array+len;
int *res = start;
while (++start != end) {
if (!(*res == *start)) {
*(++res) = *start;
}
}
int new_len=++res -array;
Else why not simply use STL ?
std::sort(array,array+len);
int *res=std::unique(array,array+len);
int new_len=res -array;