~/Home ~/Notes ~/Categories

Array Operations

18 January, 2021  ·   Dsa Arrays

Insert element in an array

1static int insert(int arr[], int n, int x, int capacity, int position) {
2    if(n == capacity) return n;
3    int idx = position - 1;
4    for(int i = n - 1; i >= idx; i--){
5    	arr[i + 1] = arr[i];
6    }
7    arr[idx] = x;
8    return n + 1;
9    }

Search for an element in an array

1static int search(int arr[], int n, int x) {
2    for(int i = 0; i < n; i++){
3    	if(arr[i] == x)
4    		return i;
5	}
6    return -1;
7}

Delete an element in an array

 1static int delete(int arr[], int n, int x){
 2   	int i = 0;
 3   	for(i = 0; i < n; i++) {
 4   		if(arr[i] == x)
 5   			break;
 6   	}
 7   	if(i == n) return n;
 8   	for(int j = i; j < n - 1; j++){
 9   		arr[j] = arr[j + 1];
10   	}
11   	return n-1;
12}

Check if an array is sorted

1static boolean isSorted(int[] arr, int n){
2	for(int i = 1; i <n; i++){
3		if(arr[i] > arr[i-1]) return false;
4	}
5	return true;
6}
 ds-algo  programming  competitive-programming
Problems on Math↠ ↞Kotlin basics