Check if array is subset of another array - c

I have two arrays.
1,3,5,7,9
{3,5} or {1.9}.
(left to right order)
So the second array is a subset of the first array
But not a subset if the second array is {5.3} or, {9.1}
(right to left order.)
My code is
#include <stdio.h>
void subset(int set11[], int set12[])
{
int length1;
int set1[] = {1, 5, 3, 9, 7, 0, 5};
length1 = sizeof(set1) / sizeof(int);
int length2;
int set2[] = {5, 9};
length2 = sizeof(set2) / sizeof(int);
int i = 0;
int j = 0;
int count = 0;
for (i = 0; i < length1; i++)
{
if (set1[i] == set2[j])
{
count = 1;
}
}
printf(" is \n");
if (count == 1)
{
printf("is subset");
}
else
{
printf("not subset");
}
}
int main()
{
int set11[] = {1, 5, 3, 9, 7};
int set12[] = {5, 9};
subset(set11, set12);
printf("");
return 0;
}
I get output in all cases only not subset.

Applied some changes in logic. refer comments.
#include <stdio.h>
#include <stdbool.h>
void subset(int set11[], int set12[])
{
int length1;
int set1[] = {1,3,5,7,9};
length1 = sizeof(set1) / sizeof(int);
int length2;
int set2[] = {3,5};
length2 = sizeof(set2) / sizeof(int);
int i = 0;
bool isSubset = true; //will indicate weather the second array is subset or not
// int j = 0; //
int startPosition = 0; // will decide the starting position for searching in the main array. {set 2}
// int count = 0; //not needed; we will represent it with bool variable 'isSubset'.
for (i = 0; i < length2; i++) //Iterating through the subset array
{
bool isFound = false;
for (int j=startPosition;j<length1;j++){ //Iterating through the original array {set 1}
if (set2[i]==set1[j]){ //if element from second array is found in first array then...
isFound = true; //found the element
startPosition = j+1; //increasing the starting position for next search in the first array.
printf("\t%d found at %d\n",set2[i],j);
break;
}
}
if(isFound==false){ //if not found then this is not subarray.
printf("\t%d not found\n",set2[i]);
isSubset = false;
break;
}
}
// printf(" is \n");
if (isSubset)
{
printf("subset");
}
else
{
printf("not subset");
}
}
int main()
{
int set11[] = {1, 5, 3, 9, 7};
int set12[] = {5, 9};
subset(set11, set12);
printf("");
return 0;
}

You can run a nested loop to get hold of all the matching elements in the subset array
for (i = 0; i < length1; i++)
{
for(k = 0; k < length2; k++)
{
if (set1[i] == set2[k])
{
count == 1;
}
}
}
Outer loop is for the for the First array
Inner loop to check for the element at any position in the subset/second array
set1[] = {1, 5, 3, 9, 7, 0, 5};
set2[] = {5, 9};
If we run a nested loop we will get all the subsets regardless of their positions in the second array(set2)
it wont matter if the set2 is {5,9} or {9,5} in any case the counter variable will increase.

Related

Find the smallest number in an array that is not in another array

Currently I am trying to solve this task: Two arrays of five integers each are given. Find the lowest number in the first array that is not in the second array.
It seems to me that if the user enters such integers in the first array:
0 1 2 3 4
And the integers of the second array:
0 2 3 4 5
The lowest integer, according to the condition of the task, will be 1, because it is not in the second array.
So here is my code:
#include <stdio.h>
#include <locale.h>
int main() {
setlocale(LC_ALL, "Rus");
int arr1[5]; //initialize arrays
int arr2[5];
printf("Enter integers\n");
for (int i = 0; i < 5; i++) {
int element;
scanf_s("%d", &element);
arr1[i] = element;
}
printf("Enter integers\n");
for (int i = 0; i < 5; i++) {
int element;
scanf_s("%d", &element);
arr2[i] = element;
}
int min1 = arr1[0];
int min2 = arr2[0];
for (int i = 0; i < 5; i++) { // algorithm for finding the minimum number of an array 1
if (min1 > arr1[i]) {
min1 = arr1[i];
}
if (min2 > arr2[i]) {
min2 = arr2[i];
}
}
}
Well, the code is very clear, but here's how to make this check, if the first array input 0 1 2 3 4 and the second 0 2 3 4 5 then how to remove this zero.
There are some issues ...
We don't care about the min value for arr2--only for arr1
We must scan all arr2 values for a match to the current/candidate value of arr1
There are some special cases we must handle
Normally, if we're just looking for the min value in arr1 (e.g. arr2 is not a factor), we can do [as you've done]:
int min1 = arr1[0];
And, we could start indexing into arr1 from 1 in the for loop.
But, this fails if:
arr1[0] is the min value in arr1 and that value is in arr2
arr1 and arr2 have identical values [even if they are in a different order].
So, we need an extra [boolean] value to denote whether the min1 value is valid. And, we must start indexing in the for loop from 0.
Here is the refactored code. It is annotated:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <locale.h>
#define A1MAX 5
#define A2MAX 5
int
main(void)
{
setlocale(LC_ALL, "Rus");
// define arrays
int arr1[A1MAX];
int arr2[A2MAX];
printf("Enter integers\n");
for (int i = 0; i < A1MAX; i++) {
if (scanf("%d", &arr1[i]) != 1) {
printf("missing arr1[%d] -- %s\n",i,strerror(errno));
return 2;
}
}
printf("Enter integers\n");
for (int i = 0; i < A2MAX; i++) {
if (scanf("%d", &arr2[i]) != 1) {
printf("missing arr2[%d] -- %s\n",i,strerror(errno));
return 3;
}
}
int nomin = 1;
int min1 = arr1[0];
// check all values in arr1
for (int i = 0; i < A1MAX; i++) {
// current value we're going to test
int val = arr1[i];
// check value if it's a _new_ minimum or we do _not_ yet have a minimum
if ((val < min1) || nomin) {
// scan all elements of arr2, looking for a match to the current
// arr1 value
int match = 0;
for (int j = 0; j < A2MAX; j++) {
match = (val == arr2[j]);
if (match)
break;
}
// if the current value is _not_ in arr2, we have a new minimum
if (! match) {
min1 = val;
nomin = 0;
}
}
}
if (nomin)
printf("there are no elements in arr1 that are not in arr2\n");
else
printf("the minimum element in arr1 not in arr2 is: %d\n",min1);
return nomin;
}
Things get complicated with code tries to maintain multiple indexes into multiple arrays... Things are simplified if you re-use code and break out functions (that can test user input, too)...
#include <stdio.h>
void fill( int arr[], size_t sz ) { // Get user input (with checking)
printf("Enter integers\n");
for( size_t i = 0; i < sz; i++ )
if( scanf( "%d", &arr[i] ) != 1 ) {
fprintf( stderr, "scanf failure\n" );
exit(1);
}
}
// Search for a value in an array. Return index if found, or size if not found
size_t hunt( int val, int arr[], size_t sz ) {
for( size_t i = 0; i < sz; i++ )
if( val == arr[i] )
return i;
return sz;
}
int main() {
#if 0 // Normal with user entry
int arr1[5], arr2[5];
size_t a1sz = sizeof arr1/sizeof arr1[0];
size_t a2sz = sizeof arr2/sizeof arr2[0];
fill( arr1, a1sz );
fill( arr2, a2sz );
#else // less tedious with compile time init of data
int arr1[] = { 0, 1, 2, 3, 4 };
int arr2[] = { 0, 2, 3, 4, 5 };
size_t a1sz = sizeof arr1/sizeof arr1[0];
size_t a2sz = sizeof arr2/sizeof arr2[0];
#endif
size_t gotOne = 0;
for( size_t i = 0; i < a1sz; i++ ) {
// don't bother testing values if got a candidate and value is larger
if( gotOne && arr1[i] >= arr1[ gotOne ] ) continue;
// following is TRUE when not found...
if( hunt( arr1[i], arr2, a2sz ) == a2sz )
gotOne = i + 1;
}
if( gotOne )
printf( "Smallest in arr1 not in arr2 = %u\n", arr1[ gotOne - 1 ] );
else
puts( "No such value matching criteria" );
return 0;
}
Smallest in arr1 not in arr2 = 1
Algorithm
The naive approach to this, and one that works very well for small datasets, is to nest a couple of loops. This approach grows in time complexity very fast. O(m*n) where m is the length of the first array and n is the length of the second array.
Fortunately, we can approach this in a way that does not involve nested loops. This assumes both arrays contain only unique values. If they have duplicates, removing those duplicates would be a necessary step before the below can be performed.
Let's start with a couple of simple arrays:
int foo[] = {1, 4, 7, 9, 2};
int bar[] = {4, 1, 6, 7, 3};
Let's combine them into another array. This is a linear operation.
{1, 4, 7, 9, 2, 4, 1, 6, 7, 3}
Let's then use qsort to sort them. This operation is typically O(n*log n).
{1, 1, 2, 3, 4, 4, 6, 7, 7, 9}
Now, we can do a linear loop over these and find the unique elements. These are the ones present in one but not both of the arrays.
{2, 3, 6, 9}
But this doesn't tell us which is in the first array. That sounds like a nested loop issue. Instead, though, let's combine that with the first array.
{1, 4, 7, 9, 2, 2, 3, 6, 9}
And we'll sort this.
{1, 2, 2, 3, 4, 6, 7, 9, 9}
Now we'll scan for the first repeated number.
2
An implementation
Note: Does not check for malloc errors.
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
int c = *(const int *)a;
int d = *(const int *)b;
if (c == d) return 0;
else if (c < d) return -1;
else return 1;
}
int min_not_in_2nd_array(int *result, int *arr1, size_t m, int *arr2, size_t n) {
int *temp = malloc(sizeof(int) * (m + n));
//if (!temp) return 0;
for (size_t i = 0; i < m; ++i) temp[i] = arr1[i];
for (size_t i = 0; i < n; ++i) temp[m+i] = arr2[i];
qsort(temp, m+n, sizeof(int), cmp);
int *uniques = malloc(sizeof(int) * (m + n));
//if (!uniques) return 0;
size_t n_uniques = 0;
int cur = temp[0] - 1;
size_t cur_count = 0;
for (size_t i = 0; i < m+n; ++i) {
if (i == m+n-1 && temp[i] != temp[i-1]) {
uniques[n_uniques++] = temp[i];
}
else if (temp[i] != cur) {
if (cur_count == 1) uniques[n_uniques++] = cur;
cur = temp[i];
cur_count = 1;
}
else {
cur_count++;
}
}
//for (size_t i = 0; i < n_uniques; ++i) printf("%d ", uniques[i]);
//printf("\n");
int *temp2 = malloc(sizeof(int) * (m + n_uniques));
// if (!temp2) return 0;
for (size_t i = 0; i < m; ++i) temp2[i] = arr1[i];
for (size_t i = 0; i < n_uniques; ++i) temp2[m+i] = uniques[i];
qsort(temp2, m+n_uniques, sizeof(int), cmp);
int found = 0;
for (size_t i = 0; i < m+n_uniques-1; ++i) {
if (temp2[i] == temp2[i+1]) {
*result = temp2[i];
found = 1;
break;
}
}
free(temp);
free(uniques);
free(temp2);
return found;
}
int main(void) {
int foo[] = {1, 4, 7, 9, 2};
int bar[] = {4, 1, 6, 7, 3};
int baz;
if (min_not_in_2nd_array(&baz, foo, sizeof(foo)/sizeof(*foo),
bar, sizeof(bar)/sizeof(*bar))) {
printf("Min not in 2nd array is %d\n", baz);
}
else {
printf("All elements shared.\n");
}
return 0;
}

Searching for matching elements between 2 arrays in C

Question
There are two arrays, one contains a large number of numbers (arr1) that may have a few repeating sequences for example 1,2,4 might repeat multiple times in this array. There is another array (arr2) that will be assigned by the user.
I need a way to search arr1 for the exact input the user gave for arr2. For a match to be valid, all the elements have to be in the exact same order as entered by the user.
For example, if the user enters 1,2,4,3 the program has to find 1,2,4,3 in that exact order in arr1, this means that 1,2,3,4 in arr1 should not be counted as a match. Below is what I have been able to come up with so far, but this returns true even if just the first element of the 2 arrays matches.
for (int i=0; i<size1; i++)
{
for (int j = 0; j<size2; j++)
{
if(arr1[i] == arr2[j])
{
printf("found a match %d", j);
break;
}
else if (arr1[i] != arr2[j])
{
printf("not match");
break;
}
Below is the complete code :-
#include <stdio.h>
#include <string.h>
int main()
{
int arr1[] = {1, 2, 4, 2, 2, 2, 1, 1, 2, 4, 3, 4, 4, 1, 2, 4, 4, 1, 3, 3};
int size1 = (int) (sizeof(arr1)/sizeof(arr1));
int arr2[] = {1, 2, 4};
int size2 = (int) (sizeof(arr2)/sizeof(arr2[0]));
int match = 0;
for (int i=0; i<size1; i++)
{
for (int j = 0; j < size2; j++) {
if (arr1[i] != arr2[j]) {
match = 1;
break;
}
}
}
if(match == 1){
printf("Not a match");
}else if(match == 0){
printf("The lists match");
}
return 0;
}
if you look at the arr1 and arr2, I need a way to return the index 0,7,13 and also this is still rough since arr2 is technically dynamic since it is assigned by the user and has no fixed size, only arr1 will have a fixed size.
Your question is similar to finding substrings in a string. But characters are replaced with integers.
Here is a program that will find the matches. It has some debug print statements to show how it works.
#include <stdio.h>
int g_Arr2_Changed=0; //----Global boolean if arr2 changes.
int main(int argc, const char *argv[])
{ int arr1[] = {1, 2, 4, 2, 2, 2, 1, 1, 2, 4, 3, 4, 4, 1, 2, 4, 4, 1, 3, 3};
int size1 = (int) (sizeof(arr1)/sizeof(int));
int arr2[] = {1, 2, 4};
int size2 = (int) (sizeof(arr2)/sizeof(int));
int patternStart = -1; //----Start pattern in arr1.
int nPatternMatch = 0; //----Number of ints matched so far.
for (int i=0; i<size1; i++)
{ int checkInt = arr1[i];
//printf("[%i](%i)", i, checkInt);
if (nPatternMatch == 0) //----No integers are matched yet.
{ //printf("<None>");
//----Is checkInt the start of arr2?
if (arr2[nPatternMatch] == checkInt)
{ patternStart=i; nPatternMatch++; //printf("<start>");
}
}
else //----At least one integer has been matched already.
{ //printf("<Some>");
//----Is checkInt a continuation?
if (arr2[nPatternMatch] == checkInt)
{ nPatternMatch++; //----Matched another integer.
//printf("<matched>");
}
else
{ //printf("<NotMatched>");
i = patternStart; //---- for() will add one.
patternStart = - 1;
nPatternMatch = 0; //----Not match. Start at next int.
}
}
//----If match found print and reset for next.
if (nPatternMatch == size2)
{ printf("Pattern found at %i\n", patternStart);
i = patternStart + 1;
patternStart = -1; nPatternMatch = 0;
}
//----Just in case the global variable says arr2 changed.
if (g_Arr2_Changed != 0) //----Start over.
{ //printf("<arr2 changed.>");
i=0; patternStart = -1; nPatternMatch = 0;
size2 = (int) (sizeof(arr2)/sizeof(int));
}
//printf("\n");
}
return 0;
}
This code will return a match for every character that is found in the same position in both lists.
So if you you want to verify the whole list, you should set an int, to identify if there is even one character that doesn't match in both lists.
If you want to show the list that match, you just have to print the whole list inside the second if.
int match = 0;
for (int i=0; i<size1; i++)
{
for (int j = 0; j < size2; j++) {
if (arr1[i] != arr2[j]) {
match = 1;
break;
}
}
if(match == 1){
printf("Not a match");
}else if(match == 0){
printf("The lists match");
printf("First character: %c", arr2[0]);
}
match = 0;
}
Would you please try the following:
#include <stdio.h>
int main()
{
int arr1[] = {1, 2, 4, 2, 2, 2, 1, 1, 2, 4, 3, 4, 4, 1, 2, 4, 4, 1, 3, 3};
int size1 = sizeof arr1 / sizeof arr1[0];
int arr2[] = {1, 2, 4};
int size2 = sizeof arr2 / sizeof arr2[0];
int match;
int i, j;
for (i = 0; i < size1 - size2 + 1; i++) {
match = 0;
for (j = 0; j < size2; j++) {
if (arr1[i + j] != arr2[j]) {
match = 1;
break;
}
}
if (! match) {
printf("matched at %d\n", i);
}
}
return 0;
}
It will output:
matched at 0
matched at 7
matched at 13
If you want to assign an array to the list of the matched indices, it will be easy for you to modify the code.

Moving all zeros to the begining of array

I'm trying to write a function which moves all numbers from begining of array to the end of it. order should not change.
for example i have this array:
1, 2, 3, 4, 5, 0, 0, 0, 0
i want to change it to:
0, 0, 0, 0, 1, 2, 3, 4, 5
I already wrote a version of it but it can't keep the order. (array[] is original and a[] is sorted)
#include <stdio.h>
#define SIZE_MAX 20
int main()
{
int array[SIZE_MAX] = {1, 2, 3, 4, 5, 0, 0, 0, 0};
int a[SIZE_MAX];
int i;
int p = 0;
for (i = SIZE_MAX-1; i >= 0; i--, p++)
{
a[i] = array[p];
}
for (i = 0; i < SIZE_MAX; i++)
{
printf("%d", a[i]);
}
}
One option would be to loop through the array twice, first copying over the zeros, then the rest of the values:
#include <stdio.h>
#define SIZE_MAX 10
int main()
{
int array[SIZE_MAX] = {1, 2, 0, 0, 3, 4, 5, 0, 0, 0};
int a[SIZE_MAX];
int i;
int p = 0;
for (i = 0; i < SIZE_MAX; ++i) {
if (array[i] == 0) {
a[p++] = 0;
}
}
for (i = 0; i < SIZE_MAX; ++i) {
if (array[i] != 0) {
a[p++] = array[i];
}
}
for (i = 0; i < SIZE_MAX; i++) {
printf("%d", a[i]);
}
}
I changed SIZE_MAX to 10, so that it matches the number of elements in the array.
The sentence "I'm trying to write a function which moves all numbers from beginning of array to the end of it." sounds like it should be done in place - and it turns out with this problem it is quite easy to do an in-place algorithm. Note that unlike other algorithms here, this just scans the array once, and writes the array once. Here I wrote it into a function:
void relocate_zeroes(size_t length, int *array) {
int *target = array + length - 1;
int *source = target;
for (; source >= array; source--) {
if (*source) {
*target-- = *source;
}
}
while (target >= array) {
*target-- = 0;
}
}
Basically we scan the source array once from end to beginning; and if we meet a non-zero integer, we relocate it just before the previous non-zero integer. When the whole array has been scanned, the area between the base (array) and target is filled with zeroes.
In the beginning both target and source point to the last value of the array; if the *source is not 0, we replace *target with *source; that is, if the last element is non-zero, we replace it by itself and decrease both target and source pointers; if the last element is 0, we don't copy it anywhere, only decrease the source pointer; continuing this way at the end we have copied all non-zero elements, and we can fill the remaining array elements with zeroes.
Given program:
#define SIZE_MAX 9
int main() {
int array[SIZE_MAX] = {1, 0, 2, 3, 0, 4, 0, 0, 5};
int i;
relocate_zeroes(SIZE_MAX, array);
for (i = 0; i < SIZE_MAX; i++) {
printf("%d ", array[i]);
}
}
The output will be
0 0 0 0 1 2 3 4 5
If the 2-array version is required, then this is easy to modify for that too:
void relocate_zeroes(size_t length, int *source_array, int *target_array) {
int *target = target_array + length - 1;
int *source = source_array + length - 1;
for (; source >= source_array; source--) {
if (*source) {
*target-- = *source;
}
}
while (target >= target_array) {
*target-- = 0;
}
}
If you need all the 0 at the beginning and rest of the numbers in same order try this :
#include <stdio.h>
#define SIZE_MAX 9
int main()
{
int array[SIZE_MAX] = {1, 2, 3, 4, 5, 0, 0, 0, 0};
int a[SIZE_MAX];
int i;
int temp[SIZE_MAX];
int ind1=0,ind2=0;
// separating all the 0's and store it at the beginning
for (i = 0; i < SIZE_MAX; i++)
{
if(array[i]==0)
a[ind1++]=0;
else
temp[ind2++]=array[i];
}
// storing rest of the numbers in order
for (i = 0; i < ind2; i++)
{
a[ind1++]=temp[i];
}
for (i = 0; i < SIZE_MAX; i++)
{
printf("%d", a[i]);
}
}
NOTE:
first i stored all the 0's in the result array and in the meantime all the non zero value are being stored in temp array.
later, i just merged the temp array to the result array.
Integer fullArray[] = { 1, 10, 20, 0, 59, 63, 0, 88, 0 };
for (int i = 0; i <= fullArray.length - 1; i++) {
if (fullArray[i] == 0 && i > 0) {
int temp = fullArray[i - 1];
if (temp != 0) {
fullArray[i - 1] = 0;
fullArray[i] = temp;
i = -1;
}
}
}
System.out.println(Arrays.asList(fullArray).toString());
Here is an in-place method using swap()
#include <stdio.h>
#define SIZE_MAX 20
swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
moveZerosLeft(int length, int *array)
{
int i = 0;
int cur = length - 1;
for( i = length - 1; i >= 0; --i)
if(array[i] != 0)
{
swap(&array[i], &array[cur--]);
}
}
int main()
{
int array[SIZE_MAX] = {1, 2, 3, 4, 5, 0, 0, 0, 0};
int i;
int length = 9;
moveZerosLeft(length, array);
// display the result
for(i = 0; i < length; i++)
{
printf("%d ", array[i]);
}
}
We scan from the right of the array to the left. When we see a non-zero value, we swap it with a zero which we saw previously.
This method requires only 1 scan of the array.
public class Demo{
public static void moveZeros() {
int[] num = {1, 0, 0 , 6, 7, 0};
int temp=-1;
for (int i = 0; i < num.length;i++)
{
if(num[i]!=0)
{
++temp;
if(num[temp] ==0){
int val = num[i];
num[i]=num[temp];
num[temp]=val;
}
else
{
num[temp]=num[i];
}
}
}
}
public static void main(String args[])
{
Demo.moveZeros();
}
}

Code that compares two non-sorted int arrays. C

I need to create a code that compares two in arrays without sorting them. They have to be the same length and contain the same elements in any order.
every integer in a[] is also in b[]
every integer in b[] is also in a[]
all such common values appear exactly the same
number of times in both a[] and b[]
Examples:
a = {1, 2, 3}, b = {2, 3, 4} return 0
a = {1, 2, 3}; b = {2, 3, 1} return 1
a = {1, 2, 2}; b = {2, 2, 1} return 1
a = {1, 2, 2}; b = {2, 1, 1} return 0
a = {1, 1, 2, 2, 2}; b = {2, 1, 2, 1, 2} return 1
I just don't know what to do for this one...
You will end up with a quadratic algorithm if the arrays are not sorted. You can check array lengths at the beginning of your algorithm and if they are equal, say N, you would do something like this
int result = 1;
for (int j=0;j<N;j++) {
bool found = false;
for (int i=0;i<N && !found;i++) {
if (a[j] == b[i]) found = true;
}
if (!found) return 0;
}
I took sometime away and got it within a minute:D
int same_contents(int a[], int b[], int n){
int maxA=0,maxB=0,counterA=0,counterB=0;
int i,k,j,x;
for(i=0; i<n; ++i)
if (a[i]>maxA)maxA=a[i];
for(i=0; i<n; ++i)
if (b[i]>maxB)maxB=b[i];
if (maxA != maxB) return 0;
for(j=0;j<n;++j){
counterA=0;
counterB=0;
for(k=0;k<n;++k){
if(maxA==b[k])counterA++;
if(maxA==a[k])counterB++;
}
if (counterA != counterB) return 0;
else continue;
}
return 1;
}
You can try this!
#include<stdio.h>
int check_same_array(int a[], int b[],int lenA,int lenB)
{
int result = 0;
bool flag = false;
int i = 0,j=0;
if (lenA != lenB)
return 0;
for (i = 0; i < lenA; i++)
{
flag = false;
for (j = 0; j < lenB; j++)
{
if (a[i] == b[j])
flag = true;
}
if (!flag)
{
result = 0;
break;
}
}
if (flag)
result = 1;
return result;
}
int main()
{
int a[5] = { 2, 2, 3, 3 ,5};
int b[5] = { 3, 3, 2, 2 ,5};
int lenA = sizeof(a) / sizeof(int);
int lenB = sizeof(b) / sizeof(int);
printf("%d\n", check_same_array(a, b, lenA, lenB) && check_same_array(b, a, lenB, lenA));
return 0;
}
check_same_array is used to check if each item in array A is in array B.
So if each item in array A is in array B,and each item in array B is in array A.
the item of the two array is same.

Issue with selection sort and using a findMin method in C

so I'm having an issue with a selection sort that I made in C. When implemented in one function, I can get the selection sort to work. However, when I do what my assignment asks, and use a findMin function that returns the minimum index an array, it doesn't sort it completely. I've tried to debug it using print statements but I can't seem to figure out what is going wrong.
Here is the sorting method I am using with the findMin method:
void sortMin2(int A[]) {
int outer;
int minIndex;
for(outer = 0; outer < 5; outer++) {
minIndex = findMin(A, outer, 5);
if(minIndex != outer) {
swap(&A[minIndex], &A[outer]);
}//end if
} // end for
}
int findMin(int A[], int i, int j) {
int k; // for loop
int index = 0;
for(k = (i + 1); k < (j+1); k++) {
if(A[k] < A[index]) {
index = k;
} // end if
} // end for
return index;
} // end findMin
void swap(int *i, int *j) {
int temp = *i;
*i = *j;
*j = temp;
} // end swap
And here is my output when I run it on an array of five values:
Array Before: 4, 10, 9, 1, 3,
4, 10, 9, 1, 3,
1, 10, 9, 4, 3,
10, 1, 9, 4, 3,
10, 1, 3, 4, 9,
10, 1, 3, 9, 4,
Array after: 4, 1, 3, 9, 10,
Now, here is my selection sort method that does work find (ie. properly sorts it).
void selectionSort2(int A[]) {
int outer; // for loops
int inner;
int minimum = 0;
//int minIndex = 0;
for(outer = 0; outer < 5; outer++) {
//minIndex = findMin(A, 0, 19);
minimum = outer;
for(inner = outer + 1; inner < 5; inner++) {
if(A[minimum] > A[inner]) {
minimum = inner;
} // end if
} // end inner for
if(minimum != outer) {
swap(&A[minimum], &A[outer]);
} // end if
} // end outer for
}
Does anyone see why my sortMin2 function doesn't actually sort it?
Some thingies, inside the code, are not in the right sense.
Why in findMin(...) method, the for loop has k < (j+1) as terminating condition. Don't you think, it should be k < j? Since j + 1 will lead to 6, hence the loop will go till j = 5, which will lead to undefined behaviour(as it is more than the bounds of the array A). Array indices start from 0. Since the size is 5, hence the indices are in the range of 0 - 4.
Moreover, the value of index is never changing. It always starts from 0 in every iteration. Instead it should be int index = i, inside the findMin(...) function, as in Selection Sort we find the smallest element, and put it on the left hand side, to it's rightful position, hence next time, we start from a place, one ahead of this location.
And inside the sortMin2(...) function, you failed to call swap(...), in case you have the new index to swap values with.
Here is the modified version, of the snippet:
int findMin(int A[], int i, int j) {
int k; // for loop
int index = i;
for(k = (i + 1); k < (j); k++) {
if(A[k] < A[index]) {
index = k;
} // end if
} // end for
return index;
} // end findMin
void swap(int *i, int *j) {
int temp = *i;
*i = *j;
*j = temp;
} // e
void display(int A[])
{
int i = 0;
for (i = 0; i < 5; ++i)
printf("%d\t", A[i]);
printf("\n");
}
void sortMin2(int A[]) {
int outer = 0;
int minIndex = -1;
for(outer = 0; outer < 5; outer++) {
minIndex = findMin(A, outer, 5);
if(minIndex != outer) {
swap(&A[minIndex], &A[outer]);
display(A);
}//end if
} // end for
}

Resources