Selection Sort in c++ - c++

i'm trying to understand selection sort from this video:
https://www.youtube.com/watch?v=79AB11J5BqU
this is my current code :
#include <iostream>
int main() {
int numbers[5]={5,3,4,1,2};
int temp;
std::cout<<"BEFORE SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
for (int i = 0; i < 5; ++i) {
for (int j = i+1; j < 5; ++j) {
if(numbers[j]<numbers[i]){
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
}
std::cout<<"\n\nAFTER SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
}
Am i doing the selection sort just like the video?
or am i instead doing buble sort ?
Thanks

In selection sort you find a minimal (or maximal) element and put it to top (bottom), then repeat it again for the rest of list.
It would be a selection sort, but you don't need to do swap every number you compare to find the smallest one. Store smallest number index in each internal loop and do one swap at the end of it.
unsigned minIndex;
for (int i = 0; i < 5; ++i) {
minIndex = i;
for (int j = i + 1; j < 5; ++j) {
if(numbers[j] < numbers[minIndex]){
minIndex = j;
}
}
if (minIndex != i) { // Do swapping
temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
}

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.
#include<iostream>
using namespace std;
// Selection Sort//
void Selection_Sort(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
int min_index=i;
for(int j=i;j<n-1;j++)
{
if(a[j]<a[min_index]){
min_index=j;
}
}
swap(a[i],a[min_index]);
}
}
int main()
{
int n,key;
cin>>n;
int a[1000];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
Selection_Sort(a,n);
for(int i=0;i<n;i++)
{
cout<<a[i];
}
}

Related

please can anyone explain me why this permutation code is not working

please can anyone point out what I have done wrong this is code for permutation which stores all possible permutation of the small vector "vec" and then display it
#include<vector>
using namespace std;
vector <vector<int>> ans;
void permut(vector<int> &vec,int index){
if(index==vec.size()){
ans.push_back(vec);
return;
}
for (int i = index ;i<index;i++){
swap(vec[i],vec[i+1]);
permut(vec,index+1);
swap(vec[i],vec[vec.size()]);
}
}
int main(){
int n; cin>>n;
vector<int> vec(n);
for(int i = 1;i<=n; i ++){
vec[i-1]= i;
}
permut(vec,0);
for (int j =0 ;j<ans.size();j++){
for(int k = 0 ; k<vec.size();k++){
cout<< vec[j]<<endl;
}
}
}
We have to run the for loop from i = start to i = end but you are running it from i = index to i < index which means your loop won't even run a single time.
#include<bits/stdc++.h>
using namespace std;
vector <vector<int> > ans;
void permut (vector <int> &vec, int start, int end){
// base case
if (start == end){
ans.push_back(vec);
} else {
for (int i = start; i <= end; i++){
swap(vec[i], vec[start]);
permut(vec, start + 1, end);
swap(vec[i],vec[start]); //backtrack
}
}
}
int main() {
int n;
cin >> n;
vector <int> vec(n);
for (int i = 0;i < n; i++) {
vec[i]= i + 1;
}
permut(vec, 0, n - 1);
for (int j = 0; j < ans.size(); j++){
for (int k = 0 ; k < vec.size(); k++){
cout<< ans[j][k];
}
cout << endl;
}
}

How to make a function that remove duplicates from an passed array

It's my first year learning the C++ language. I want to make a function that removes duplicates from a passed array. I tried to doing it with many different kinds of logic, but sadly I have failed on all of them. I hope someone can help me.
Here is my code:
using namespace std;
#include <iostream>
void RemoveDuplicates(int * array,int n,int *&arrayb)
{
int x=0;
int y=0;
for (int i=0;i<n;i++)
{
y++;
if (array[x]!=array[y])
{
arrayb[x]=array[x];
x++;
y++;
}
else
{
arrayb[x]=array[x];
x++;
y++;
break;
}
}
}
int main()
{
int n;
cin >> n;
int * array = new int [n];
int * arrayb = new int [n];
int i=0;
for (i=0;i<n;i++)
{
cin>>array[i];
}
RemoveDuplicates(array,n,arrayb);
for (int i=0;i<n;i++)
{
cout << arrayb[i] <<" ";
}
system("pause");
}
My two cents on this, I had this piece of code in my repo
void remove_duplicates(int arr[], int &a_size) {
for (int i = 0; i < a_size; i++) {
for (int j = i + 1; j < a_size;j++) {
if (arr[i] == arr[j]) {
for (int k = j; k < a_size; k++) {
arr[k] = arr[k + 1];
}
a_size--;
j--;
}
}
}
}

find frequency in array using vector

How can I change my code to get a count for every element?
With my code everything is okay. And it works, but how can I change only that part?
#include <iostream>
#include <vector>
void countFreq(int arr[], int n)
{
// Mark all array elements as not visited
std::vector<bool> visited(n, false);
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
// Skip this element if already processed
if (visited[i] == true)
continue;
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
visited[j] = true;
count++;
}
}
std::cout<<count<<" ";
}
}
int main()
{
int n;
std::cin>>n;
int arr[n];
for(int i = 0; i < n; i++){
std::cin>>arr[i];
}
countFreq(arr, n);
return 0;
}
And about the result`
input 10
1 1 2 2 3 3 4 4 5 5
output 2 2 2 2 2
but I want to get
output 2 2 2 2 2 2 2 2 2 2
(for every element)
Your function contains extra code that ends up confusing you. The visited variable is essentially unnecessary. Start the count at 0 and make no special case for the "current" cell and you'll find that some very simple code will do what you need:
void countFreq(int arr[], int n)
{
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
// Count frequency
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
std::cout << count << " ";
}
}
You need to save the result to an array for each number. Then when you find any processed number then print counter from the saved array.
#include <iostream>
#include <vector>
#include <unordered_map>
void countFreq(int arr[], int n)
{
// Mark all array elements as not visited
std::vector<bool> visited(n, false);
std::unordered_map<int, int> counter;
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++)
{
// Skip this element if already processed
if (visited[i] == true)
{
std::cout << counter[arr[i]] << " ";
continue;
}
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++)
{
if (arr[i] == arr[j])
{
visited[j] = true;
count++;
}
}
counter[arr[i]] = count;
std::cout<<count<<" ";
}
}
int main()
{
int n;
std::cin>>n;
int arr[n];
for(int i = 0; i < n; i++)
{
std::cin>>arr[i];
}
countFreq(arr, n);
return 0;
}
The issue is that you discard the values already visited.
One possibility is instead to memorize the count when the value is visited the first time,
and to memorize the index value of the first value appearance, when a value is visited the 2nd, 3rd ... time.
#include <iostream>
#include <vector>
void countFreq(const std::vector<int>& arr) {
int n = arr.size();
// Mark all array elements as not visited
std::vector<int> mem_count(n, n);
// Traverse through array elements and
// count frequencies
for (int i = 0; i < n; i++) {
// Skip this element if already processed
if (mem_count[i] != n) {
std::cout << mem_count[mem_count[i]] << " ";
continue;
}
// Count frequency
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
mem_count[j] = i;
count++;
}
}
mem_count[i] = count;
std::cout << count << " ";
}
}
int main() {
int n;
std::cin>>n;
std::vector<int> arr(n);
for(int i = 0; i < n; i++){
std::cin >> arr[i];
}
countFreq(arr);
return 0;
}
You can find the frequencies of numbers this way if you know the what is your maximum element in the input array. lets say m is maximum number in your array.
so you have to create a new array of size m. you can simply co-relate them as m buckets. from 0 to m. And each bucket will hold the count of each element in the input array. The index of each bucket will refer to element in the input array. This has time complexity O(1) if we know what is the max element the array.
You can do this way:
std::vector<int> frequencey(std::vector<int>& nums){
auto max = *(std::max_element(nums.begin(), nums.end()));
std::vector<int> frequencies(max + 1, 0);
for(int i = 0; i < nums.size(); ++i){
frequencies[nums[i]] +=1;
}
return frequencies;
}
This is very simple
#include <vector>
#include <map>
#include <iostream>
void main()
{
std::vector<int> v { 1,1,2,2,3,3,4,4,5,5 }; // Your input vector
// Count "frequencies"
std::map<int, int> m;
for (auto i : v)
m[i]++;
// Print output
for (auto i : v)
std::cout << m[i] << " ";
}

How can i repeat my bubble sort one it get executed?

I am trying to do the bubble sort? In my code, i already partially sort my array one time. I want to do this step again to sort full of my array and then exit the programme.
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int A[n];
for(int i=0;i<n;i++)
{
cin>>A[i];
}
for(int i=0;i<n;i++)
{
cout<<A[i];
}
cout<<endl;
//repet:;
for(int i=0;i<n;i++)
{
while(A[i]>A[i+1])
{
int temp;
temp = A[i+1];
A[i+1] = A[i];
A[i] = temp;
}
for(int i=0;i<n;i++)
{
cout<<A[i];
}
cout<<endl;
}
//goto repet;
return 0;
}
I have used another loop and a boolean var swapped to check in this iteration if anything changed.
bool swapped;
do {
swapped = false;
for(int i=0;i<n;i++)
{
while(A[i]>A[i+1])
{
int temp;
temp = A[i+1];
A[i+1] = A[i];
A[i] = temp;
swapped = true;
}
}
for(int i=0;i<n;i++)
{
cout<<A[i] << " " ;
}
cout<<endl;
} while (swapped);
You may check some optimizations in wiki.
Here is the code changes you need:
for(i = 1; (i <= numLength); i++)
{
flag = 0;
for (j=0; j < (numLength -1); j++)
{
if (num[j+1] > num[j])
{
temp = num[j]; // swaping elements
num[j] = num[j+1];
num[j+1] = temp;
}
}
}

C++ sorting an array in ascending order Printing

Im trying to sort an array in ascending order and print it out and Im having trouble of where to put my cout in my code.
for (int k=0; k<ARRAY_SIZE; k++) {
for (int l=1; l<ARRAY_SIZE-1; l++) {
if(numbers[l] > numbers[k]) {
temp = numbers[k];
numbers[k] = numbers[l];
numbers[l] = temp;
}
cout<<numbers[k];
}
}
If you want to see the result of sorting you have to print the array in new for loop
Remove the actual cout and put it after the sorting loop, in a new loop
for(int k = 0 ; k < ARRAY_SIZE; ++k)
cout << numbers[k] << " ";
This is a program that finds the length of a number n and converts it to an array arr and sorts that array in ascending order.(possible aptitude question)
#include <iostream>
using namespace std;
int main()
{
int n,i=0,j,num,temp,len=0,arr[10]={0};
cin>>n;
num=n;
while(n!=0)
{
len++;
n/=10;
}
cout<<len<<endl;
for ( i = len; i >= 0; i--)
{
arr[i] = num%10;
num/=10;
}
for(i=1;i<=len;i++)
for(j=0;j<=len-i;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
for(i=1;i<=len;i++)
{
cout<<arr[i]<<endl;
}
return 0;
}
try this :
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
//array declaration
int arr[] = {1,2,5,8,4,3};
int n,i,j;
n = sizeof(arr) / sizeof(arr[0]);
int temp;
//print input elements
cout<<"Unsorted Array elements:"<<endl;
for(i=0;i<n;i++)
if(arr[i] == arr[n - 1]){
cout<<arr[i]<<"";
}else{
cout<<arr[i]<<",";
}
cout<<endl;
//sorting - ASCENDING ORDER
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
temp =arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
//print sorted array elements
cout<<"Sorted (Ascending Order) Array elements:"<<endl;
for(i=0;i<n;i++)
if(arr[i] == arr[n - 1]){
cout<<arr[i]<<"";
}else{
cout<<arr[i]<<",";
}
cout<<endl;
return 0;
}