Organized
Organized
Arrays are an important data structure used to store collections of data. Arrays can
store multiple types of data, such as integers, strings, floats, and objects. There are several
types of arrays in data structure:
A. Traversing
To traverse an array means to access each element (item) stored in the array
so that the data can be checked or used as part of a process.
Traversing arrays involves looping through each element in the array and
processing each element one at a time. This allows you to access all array elements
and perform tasks such as printing, copying, comparing, or sorting.
int arr[50], size ;
//Position validation
if(pos<=0 || pos> size) {
cout<<"Invalid position..."<<endl;
}
else {
for(int i = pos-1; i<size -1 ; i++){
arr[i]=arr[i+1];
}
size--;
D. Searching (Linear)
It's a process of identifying an element from within an array by comparing it to your
desired value until you find a match. There are two distinct types of searches: linear and
binary search techniques, both offering varying degrees of efficiency when used correctly.
Linear search compares each element one after another until a match is found or all elements
have been searched.
//DATA
cout<<"\n\n";
cout<<"Enter data to insert :";
cin>>num;
cout<<"Enter position :";
cin>>pos;
///////////////////////////////////
//INSERTION
///////////////////////////////////
for(int i = size -1; i >=pos-1; i--) {
arr[i+1]= arr[i];
}
arr[pos-1]=num; //inserting number
size++;
#include <iostream>
using namespace std;
//Traversal
int main()
{
int arr[50], size, num, pos ;
cout<<"\n";
cout<<"\nElements of Array after Insertion:"<<endl;
cout<<"Index:"<<endl;
for(int i = 0; i<size; i++){
cout<<i<<"\t";
}
cout<<endl;
cout<<"Position:"<<endl;
for(int i = 0; i<size; i++){
cout<<i+1<<"\t";
}
cout<<endl;
for(int i = 0; i<size; i++) {
cout<<arr[i]<<"\t";
}
cout<<endl;
return 0;
}
Bubble Sort:
1. Sorting
Sorting is a process of arranging elements of an array in either ascending or descending
order. Array sorting can be done using different algorithms like bubble sort, insertion sort,
selection sort, and quick sort. Bubble sort swaps adjacent elements if they are not
ordered correctly, while selection sort finds the smallest element and shifts it to the
beginning.
size=5;
Given:
15 16 6 8 5
Pass 1:
15 16 6 8 5 i=0 No swapping to be done (15<16)
15 16 6 8 5 Comparing; swapping
…
15 6 16 8 5 …
…
15 6 8 16 5 …
…
15 6 8 5 16 Bubble up to its right position.
Pass 2:
15 6 8 5 16 i=1
6 15 8 5 16
6 8 15 5 16
6 8 5 15 16
6 8 5 15 16
Pass 3:
6 8 5 15 16 i=2
6 8 5 15 16
6 5 8 15 16
6 5 8 15 16
6 5 8 15 16
Pass 4:
6 5 8 15 16 i=3
5 6 8 15 16
5 6 8 15 16
5 6 8 15 16
5 6 8 15 16
int arr[50], size, num, temp ;
//Bubble Sort
for(int i =0; i<size-1; i++){
for(int j=0; j<size-1;j++){
if(arr[j]>arr[j+1]){
temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
//DISPLAY
cout<<endl<<endl;
for(int i = 0; i<size; i++) {
cout<<arr[i]<<"\t";
}
///////////
return 0;