C++ DSA Codes (Questions)
C++ DSA Codes (Questions)
#include <iostream.h>
#include <conio.h>
int findLargestElementIndex(int DATA[], int N) {
int LOC = 0;
int MAX = DATA[0];
for (int K = 1; K < N; K++) {
if (MAX < DATA[K]) {
LOC = K;
MAX = DATA[K];
}
}
return LOC;
}
int main() {
int DATA[] = {5, 10, 3, 8, 15};
int N = 5;
int LOC = findLargestElementIndex(DATA, N);
int MAX = DATA[LOC];
cout << "Largest element is " << MAX << " at index " << LOC << endl;
return 0;
}
// Linear search
#include <iostream.h>
#include <conio.h>
int linearSearch(int DATA[], int N, int ITEM) {
int LOC = 0;
int K = 1;
while (LOC == 0 && K <= N) {
if (ITEM == DATA[K - 1]) {
LOC = K;
}
K++;
}
return LOC;
}
int main() {
int DATA[] = {5, 10, 3, 8, 15};
int N = 5;
int ITEM = 8;
int LOC = linearSearch(DATA, N, ITEM);
if (LOC == 0) {
cout << "ITEM is not in the array DATA." << endl;
} else {
cout << "LOC is the location of ITEM: " << LOC << endl;
}
return 0;
}
return 0;
}
// Traversing an array
#include <iostream.h>
#include <conio.h>
void printArray(int LA[], int LB, int UB) {
int K = LB;
while (K < UB) {
cout << LA[K] << " ";
K++;
}
}
int main() {
int LA[] = {3, 6, 2, 8, 4};
int LB = 0;
int UB = 4;
printArray(LA, LB, UB);
return 0;
}
// Bubble Sort
#include <iostream.h>
#include <conio.h>
void bubbleSort(int DATA[], int N) {
for (int K = 0; K < N; K++) {
int PTR = 0;
while (PTR < N - K - 1) {
if (DATA[PTR] > DATA[PTR + 1]) {
int temp = DATA[PTR];
DATA[PTR] = DATA[PTR + 1];
DATA[PTR + 1] = temp;
}
PTR++;
}
}
}
int main() {
int DATA[] = {5, 3, 8, 2, 7};
int N = 5;
bubbleSort(DATA, N);
cout << "Sorted array: ";
for (int i = 0; i < N; i++) {
cout << DATA[i] << " ";
}
cout << endl;
return 0;
}